翻譯|使用教程|編輯:龔雪|2023-10-24 11:34:10.233|閱讀 92 次
概述:本文將重點介紹如何在MyEclipse中集成JPA-Spring以及如何利用這些功能,歡迎下載最新版IDE體驗~
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
本教程中介紹一些基于JPA/ spring的特性,重點介紹JPA-Spring集成以及如何利用這些功能。您將學習如何:
在上文中(點擊這里回顧>>),我們為大家介紹了如何用JPA和Spring Facets創建一個Java項目以及逆向工程,本文將繼續介紹如何創建一個應用并啟用容器管理的事務等。
MyEclipse技術交流群:742336981 歡迎一起進群討論
現在已經生成了所有這些代碼,您可以快速地專注于編寫“業務邏輯”,或者更具體地說,“實際執行任務的代碼”。
JPA教程介紹了每個實體和DAO類的功能,以及運行一個簡單場景的主要方法的基本大綱,包括:
類似地,在本教程中您將看到如何使用Spring獲取和使用DAO以及管理事務。
這個演示的起點是RunJPA.java類,看看這個類中的main方法。
/* 1. Initialize the transactionManager and DAO */ ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml"); txManager = ((JpaTransactionManager) ctx.getBean("transactionManager")); dao = ProductlineDAO.getFromApplicationContext(ctx); /* 2. Create a reference to our ID */ String productlineID = "Men Shoes"; /* 3. Save a new productline to the DB */ saveProductline(productlineID); /* 4. Load the productline from DB to make sure it worked */ loadProductline(productlineID); /* 5. Update the productline in the DB and check it */ updateProductline(productlineID); /* 6. Delete the productline from the DB */ deleteProductline(productlineID);
用藍色標記的代碼部分是Spring調用,您可以在其中從bean配置中檢索已配置的bean。請注意,由于您正在手動管理事務,因此還需要從bean配置中檢索' transactionManager '。
剩下的項目,#2 - #6,簡單地調用每個“做某事”的方法。
第一個有趣的方法是“saveProductline”,此方法的目的是創建一個新實體并將其存儲在DB中。
/* 1. Create a new Productline instance */ Productline newProductline = new Productline(productlineID, "Shoes formen.", "<strong>MenShoes</strong>", null); /* 2. Store our new product line in the DB */ TransactionStatus status = txManager .getTransaction(new DefaultTransactionDefinition()); dao.save(newProductline); txManager.commit(status);
首先,用一些基本值創建新的Productline實例。其次使用transactionManager,事務在將實體保存到DB之前開始。在保存實體之后,事務被提交。
手動管理事務的目的是因為作為開發人員,您知道“保存”操作的范圍。根據應用程序的編寫方式,一些操作的作用域可能包含許多數據庫修改,將所有這些都包裝在一個事務中是很重要的,以防在工作進行到一半時失敗。您肯定不希望讓數據處于一種狀態,其中一些是正確的,而另一些是過時的。
下一個方法使用分配給實體的ID從DB中檢索實體,并顯示其值,這確認保存操作成功。
/* 1. Now retrieve the new product line, using the ID we created */ Productline loadedProductline = dao.findById(productlineID); /* 2. Print out the product line information */ System.out.println("*NEW* Product Line [productLine=" + loadedProductline.getProductline() + ", textDescription=" + loadedProductline.getTextdescription() + "]");
注意在這段代碼中,沒有使用任何事務。原因是這段代碼只執行讀操作而不執行寫操作,即使操作失敗,DB中的任何數據都不會受到影響。因此,不需要使用事務來保護操作。
現在下一段代碼看起來可能更長,但這是因為它輸出了新值,并確認在DB中更新了記錄。
/* 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() + "]");
請注意更新調用被封裝在事務中,因為它必須向數據庫寫入一些內容,并且需要防止失敗。
在上面的第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”實現類似,您會注意到一個事務用于封裝“delete”調用,然后代碼嘗試從DB加載實體并確認操作應該失敗。
注意:事務必須封裝'findById '和'delete '方法調用的原因是因為JPA管理的對象必須是同一事務的一部分,要擦除已加載的對象,它必須處于加載它并嘗試擦除它的同一個事務中。
運行此命令的輸出如下所示:
紅色文本是可以忽略的默認日志消息(如果希望控制日志記錄,您可以設置自定義log4j.properties文件),在日志警告下面,您可以看到來自TopLink (JPA實現庫)的兩條消息,以及來自實現的另外三條消息。
第一個消息打印出添加的新產品線信息,第二個消息更新產品線信息并打印新信息,最后一個消息從DB中刪除產品線信息并打印確認消息。
除了用戶管理的事務之外,Spring還通過@Transactional屬性支持容器管理的事務。對于容器管理的事務支持,您必須在添加facet時啟用它,這是您在本教程前面所做的。
啟用此功能將向bean配置文件添加以下事務元素,您還應該添加一個JPAServiceBean,它用于使用容器管理的事務刪除實體。請參閱下面的實現:
JPAServiceBean實現如下所示;注意'deleteProductLine '方法上的'@Transactional '注釋和沒有任何用戶管理的事務語句。
public class JPAServiceBean { private IProductlineDAO dao; @Transactional public void deleteProductLine(String productlineID) { /* 1. Now retrieve the new product line, using the ID we created */Productline loadedProductline = dao.findById(productlineID); /* 2. Now let's delete the product line from the DB */ dao.delete(loadedProductline); /* * 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"));} public void setProductLineDAO(IProductlineDAO dao) { this.dao = dao; } }
從應用程序上下文中獲取JPAServiceBean實例,并按如下方式使用它:
JPAServiceBean bean = (JPAServiceBean) ctx.getBean("JPAServiceBean"); bean.deleteProductLine(productlineID);
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:慧都網