MyEclipse持续性开发教程:用JPA和Spring管理数据(三)

MyEclipse红运年货节 在线购买低至69折!火爆开抢>>

MyEclipse最新版下载

本教程介绍了MyEclipse中的一些基于JPA / Spring的功能。有关设置JPA项目的基础知识,请先阅读JPA教程。 本教程主要关注MyEclipse中的JPA-Spring集成以及如何利用这些函数。您将学习到:

  • 为JPA和Spring建立一个项目
  • 反向设计一个数据库表来生成实体
  • 实现创建,检索,编辑和删除功能
  • 启用容器管理的事务

持续时间:30分钟

没有MyEclipse? 现在下载

三、写一个应用程序

现在MyEclipse已经生成了所有这些代码,您可以快速地编写您的业务逻辑。

JPA教程涵盖了实体和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”的方法。

3.1 保存一个实体

第一个有趣的方法是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修改。 把这些全部包装在一个单独的交易中是非常重要的,以防万一中途失败。

3.2 检索一个实体

下一个方法使用分配给它的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() + "]");

注意在这个代码中,没有使用事务。 原因是这个代码只执行一个读操作而不是一个写操作。 即使操作失败,也不会影响数据库中的数据。 所以,没有必要保护使用交易的操作。

更多资讯敬请访问MyEclipse中文网>>

原文地址:https://www.cnblogs.com/AABBbaby/p/8425866.html