MyEclipse红运年货节 在线购买低至69折!火爆开抢>>数据库
【MyEclipse最新版下载】eclipse
本教程介绍了MyEclipse中的一些基于JPA / Spring的功能。有关设置JPA项目的基础知识,请先阅读JPA教程。 本教程主要关注MyEclipse中的JPA-Spring集成以及如何利用这些函数。您将学习到:函数
持续时间:30分钟学习
没有MyEclipse? 如今下载ui
如今代码的下一部分可能看起来更长,但这是由于会打印出新的值,并确认记录已在数据库中更新。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节中,产品线在更新后当即从数据库加载,并打印出从数据库返回的值以确认更新。日志
删除实体与保存和更新实体几乎相同。 工做被封装在一个交易中,而后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管理的对象必须是同一个事务的一部分。 要删除加载的对象,它必须在它被加载的同一个事务中,试图将其删除。
运行它的输出以下所示:
输出
红色文本是能够忽略的默认日志消息(若是要控制日志记录,能够设置自定义log4j.properties文件)。 在日志警告的下面,您会看到两条来自TopLink(JPA实现库)的消息,而后是三条消息所有来自实现。
第一条消息打印出已添加的新产品线信息,第二条更新消息并打印新信息,最后一条消息从数据库中删除并打印确认消息。