MyEclipse紅運年貨節 在線購買低至69折!火爆開搶>>java
【MyEclipse最新版下載】數據庫
本教程介紹了MyEclipse中的一些基於JPA / Spring的功能。有關設置JPA項目的基礎知識,請先閱讀JPA教程。 本教程主要關注MyEclipse中的JPA-Spring集成以及如何利用這些函數。您將學習到:app
持續時間:30分鐘eclipse
沒有MyEclipse? 如今下載函數
如今MyEclipse已經生成了全部這些代碼,您能夠快速地編寫您的業務邏輯。學習
JPA教程涵蓋了實體和DAO類所作的每一個操做以及運行簡單場景的主要方法基本概述,其中包括:ui
一樣,在本教程中,您將看到如何使用Spring獲取和使用DAO以及管理事務。這個演示的起點是RunJPA.java類,看看這個類的主要方法。spa
/* 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」的方法。orm
第一個有趣的方法是saveProductline,此方法的目的是建立一個新的實體並將其存儲在數據庫中。
/* 1. Create a new Productline instance */ Productline newProductline = new Productline(productlineID, "Shoes formen.", "MenShoes", 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() + "]");
注意在這個代碼中,沒有使用事務。 緣由是這個代碼只執行一個讀操做而不是一個寫操做。 即便操做失敗,也不會影響數據庫中的數據。 因此,沒有必要保護使用交易的操做。