MyEclipse紅運年貨節 在線購買低至69折!火爆開搶>>數據庫
【MyEclipse最新版下載】eclipse
本教程介紹了MyEclipse中的一些基於JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀JPA教程。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。您將學習到:函數
持續時間:30分鐘學習
沒有MyEclipse? 如今下載ui
如今代碼的下一部分可能看起來更長,但這是由於會打印出新的值,並確認記錄已在數據庫中更新。spa
/* 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加載實體並確認操做失敗。blog
注意:事務必須封裝findById和delete方法調用的緣由是由於由JPA管理的對象必須是同一個事務的一部分。 要刪除加載的對象,它必須在它被加載的同一個事務中,試圖將其刪除。
運行它的輸出以下所示:
輸出
紅色文本是能夠忽略的默認日誌消息(若是要控制日誌記錄,能夠設置自定義log4j.properties文件)。 在日誌警告的下面,您會看到兩條來自TopLink(JPA實現庫)的消息,而後是三條消息所有來自實現。
第一條消息打印出已添加的新產品線信息,第二條更新消息並打印新信息,最後一條消息從數據庫中刪除並打印確認消息。