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

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

MyEclipse最新版下载eclipse

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

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

持续时间:30分钟学习

没有MyEclipse? 如今下载ui

3、写一个应用程序

3.3 更新实体

如今代码的下一部分可能看起来更长,但这是由于会打印出新的值,并确认记录已在数据库中更新。spa

/* 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() + "]");

注意update调用是用一个事务封装的,由于它必须向数据库写入一些东西,而且须要防止失败。设计

在上面的第3节中,产品线在更新后当即从数据库加载,并打印出从数据库返回的值以确认更新。日志

3.4 删除一个实体

删除实体与保存和更新实体几乎相同。 工做被封装在一个交易中,而后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实现相似,您会注意到事务用于包装删除调用,而后代码尝试从DB加载实体并确认操做失败。blog

注意:事务必须封装findById和delete方法调用的缘由是由于由JPA管理的对象必须是同一个事务的一部分。 要删除加载的对象,它必须在它被加载的同一个事务中,试图将其删除。

3.5 运行程序

运行它的输出以下所示:

输出

红色文本是能够忽略的默认日志消息(若是要控制日志记录,能够设置自定义log4j.properties文件)。 在日志警告的下面,您会看到两条来自TopLink(JPA实现库)的消息,而后是三条消息所有来自实现。

第一条消息打印出已添加的新产品线信息,第二条更新消息并打印新信息,最后一条消息从数据库中删除并打印确认消息。

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

相关文章
相关标签/搜索