原創|使用教程|編輯:龔雪|2018-02-27 10:25:07.000|閱讀 289 次
概述:本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀JPA教程。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
MyEclipse紅運年貨節 在線購買低至69折!
【】
本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。您將學習到:
持續時間:30分鐘
沒有MyEclipse?
現在代碼的下一部分可能看起來更長,但這是因為會打印出新的值,并確認記錄已在數據庫中更新。
/* 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調用是用一個事務封裝的,因為它必須向數據庫寫入一些東西,并且需要防止失敗。
在上面的第3節中,產品線在更新后立即從數據庫加載,并打印出從數據庫返回的值以確認更新。
刪除實體與保存和更新實體幾乎相同。 工作被封裝在一個交易中,然后DAO被告知要做這項工作。
/* 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實現類似,您會注意到事務用于包裝刪除調用,然后代碼嘗試從DB加載實體并確認操作失敗。
注意:事務必須封裝findById和delete方法調用的原因是因為由JPA管理的對象必須是同一個事務的一部分。 要刪除加載的對象,它必須在它被加載的同一個事務中,試圖將其刪除。
運行它的輸出如下所示:
紅色文本是可以忽略的默認日志消息(如果要控制日志記錄,可以設置自定義log4j.properties文件)。 在日志警告的下面,您會看到兩條來自TopLink(JPA實現庫)的消息,然后是三條消息全部來自實現。
第一條消息打印出已添加的新產品線信息,第二條更新消息并打印新信息,最后一條消息從數據庫中刪除并打印確認消息。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都控件網