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() + "]");
注意在这个代码中, 没有使用事务 原因是这个代码只执行一个读操作而不是一个写操作 即使操作失败, 也不会影响数据库中的数据 所以, 没有必要保护使用交易的操作
来源: https://www.evget.com/article/2018/2/7/27761.html