原創|使用教程|編輯:龔雪|2018-02-07 10:28:41.000|閱讀 278 次
概述:本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀JPA教程。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
MyEclipse紅運年貨節 在線購買低至69折!
【】
本教程介紹了MyEclipse中的一些基于JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。您將學習到:
持續時間:30分鐘
沒有MyEclipse?
現在MyEclipse已經生成了所有這些代碼,您可以快速地編寫您的業務邏輯。
涵蓋了實體和DAO類所做的每個操作以及運行簡單場景的主要方法基本概述,其中包括:
同樣,在本教程中,您將看到如何使用Spring獲取和使用DAO以及管理事務。這個演示的起點是RunJPA.java類,看看這個類的主要方法。
/* 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簡單地調用每個 “do something”的方法。
第一個有趣的方法是saveProductline,此方法的目的是創建一個新的實體并將其存儲在數據庫中。
/* 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() + "]");
注意在這個代碼中,沒有使用事務。 原因是這個代碼只執行一個讀操作而不是一個寫操作。 即使操作失敗,也不會影響數據庫中的數據。 所以,沒有必要保護使用交易的操作。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@ke049m.cn
文章轉載自:慧都控件網