原創(chuàng)|使用教程|編輯:龔雪|2018-02-27 10:25:07.000|閱讀 297 次
概述:本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關(guān)設(shè)置JPA項(xiàng)目的基礎(chǔ)知識(shí),請(qǐng)先閱讀JPA教程。 本教程主要關(guān)注MyEclipse中的JPA-Spring集成以及如何利用這些函數(shù)。
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
MyEclipse紅運(yùn)年貨節(jié) 在線購(gòu)買低至69折!
【】
本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關(guān)設(shè)置JPA項(xiàng)目的基礎(chǔ)知識(shí),請(qǐng)先閱讀。 本教程主要關(guān)注MyEclipse中的JPA-Spring集成以及如何利用這些函數(shù)。您將學(xué)習(xí)到:
持續(xù)時(shí)間:30分鐘
沒(méi)有MyEclipse?
現(xiàn)在代碼的下一部分可能看起來(lái)更長(zhǎng),但這是因?yàn)闀?huì)打印出新的值,并確認(rèn)記錄已在數(shù)據(jù)庫(kù)中更新。
/* 1. Now retrieve the new product line, using the ID we created */
Productline loadedProductline = dao.findById(productlineID);
/*
* 2. Now let's change same value on the product line, and save the
* change
*/
loadedProductline.setTextdescription("Product line for men's shoes.");
TransactionStatus status = txManager .getTransaction(new DefaultTransactionDefinition());
dao.update(loadedProductline);
txManager.commit(status);
/* * 3. Now let's load the product line from the DB again, and make sure
* its text description changed
*/
Productline secondLoadedProductline = dao.findById(productlineID);
System.out.println("*REVISED* Product Line [" + "productLine="
+ secondLoadedProductline.getProductline()
+ ", textDescription="
+ secondLoadedProductline.getTextdescription() + "]");
注意update調(diào)用是用一個(gè)事務(wù)封裝的,因?yàn)樗仨毾驍?shù)據(jù)庫(kù)寫(xiě)入一些東西,并且需要防止失敗。
在上面的第3節(jié)中,產(chǎn)品線在更新后立即從數(shù)據(jù)庫(kù)加載,并打印出從數(shù)據(jù)庫(kù)返回的值以確認(rèn)更新。
刪除實(shí)體與保存和更新實(shí)體幾乎相同。 工作被封裝在一個(gè)交易中,然后DAO被告知要做這項(xiàng)工作。
/* 1. Now retrieve the new product line, using the ID we created */
TransactionStatus status = txManager
.getTransaction(new DefaultTransactionDefinition());
Productline loadedProductline = dao.findById(productlineID);
/* 2. Now let's delete the product line from the DB */
dao.delete(loadedProductline);
txManager.commit(status);
/*
* 3. To confirm the deletion, try and load it again and make sure it
* fails
*/
Productline deletedProductline = dao.findById(productlineID);
/*
* 4. We use a simple inline IF clause to test for null and print
* SUCCESSFUL/FAILED
*/
System.out.println("Productline deletion: "
+ (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));
與上面的updateProductline實(shí)現(xiàn)類似,您會(huì)注意到事務(wù)用于包裝刪除調(diào)用,然后代碼嘗試從DB加載實(shí)體并確認(rèn)操作失敗。
注意:事務(wù)必須封裝findById和delete方法調(diào)用的原因是因?yàn)橛蒍PA管理的對(duì)象必須是同一個(gè)事務(wù)的一部分。 要?jiǎng)h除加載的對(duì)象,它必須在它被加載的同一個(gè)事務(wù)中,試圖將其刪除。
運(yùn)行它的輸出如下所示:
紅色文本是可以忽略的默認(rèn)日志消息(如果要控制日志記錄,可以設(shè)置自定義log4j.properties文件)。 在日志警告的下面,您會(huì)看到兩條來(lái)自TopLink(JPA實(shí)現(xiàn)庫(kù))的消息,然后是三條消息全部來(lái)自實(shí)現(xiàn)。
第一條消息打印出已添加的新產(chǎn)品線信息,第二條更新消息并打印新信息,最后一條消息從數(shù)據(jù)庫(kù)中刪除并打印確認(rèn)消息。
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請(qǐng)務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請(qǐng)郵件反饋至chenjj@ke049m.cn
文章轉(zhuǎn)載自:慧都控件網(wǎng)