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() + "]");
注意在这个代码中,没有使用事务。 缘由是这个代码只执行一个读操做而不是一个写操做。 即便操做失败,也不会影响数据库中的数据。 因此,没有必要保护使用交易的操做。