快速业务通道

使用Apache OpenJPA开发EJB 3.0应用,第2部分:开发第一个Open JPA应用 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-15
第2部分:开发第一个Open JPA应用(6) 时间:2011-08-31 IBM 肖菁

操作持久化对象

调用 EntityManager 的 persist 方法可以持久化对象到数据库中;

调用 EntityManager 的 merge 方法可以更新对象状态;

调用 EntityManager 的 remove 方法可以删除持久化对象,另外一种选择是 通过 Query 接口删除对象。

查询持久化对象

根据对象的主键查找符合条件的对象,可以直接使用 EntityManager 的 find 方法;

要查询 EntityManager 中符合条件的对象列表,还需要借助 Query 接口和 JPQL(Java Persistence Query Language)查询语言。

下面的章节中我们将逐一了解如何通过 OpenJPA 中的相关接口完成这些步骤 。

获取 OpenJPA 容器中的 EntityManagerFactory

EntityManagerFactory 是 OpenJPA 中创建 EntityManager 的工厂,要想得 到 EntityManager,就必须获取的相应的 EntityManagerFactory。

EntityManagerFactory 通过 Persistence 的静态方法 createEntityManagerFactory 获得,该方法是一个重载的方法,支持不同的输入 参数。最常用的是使用一个字符串作为参数,该字符串的内容是 EntityManagerFactory 的标识名,该标识名需要和 persistence.xml 文件中的 persistence-unit 元素的 name 属性保持一致。可以使用 null 作为 createEntityManagerFactory 方法的参数,这时候将使用 persistence.xml 中 没有提供 name 属性的 persistence-unit 元素提供的参数来配置 EntityManagerFactory。

下面的代码段可以从 OpenJPA 容器中获取名为“mysql”的 EntityManagerFactory。

EntityManagerFactory factory =  Persistence.createEntityManagerFactory("mysql");

而它对应的 persistence.xml 文件中,应该有相应的 name 属性为“mysql” 的 persistence-unit 元素,下面的配置是一个示例。

1. <persistence  xmlns="http://java.sun.com/xml/ns/persistence" 2.   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3.   version="1.0"> 4.   <persistence-unit name="mysql" transaction- type="RESOURCE_LOCAL"> 5. … 6.   </persistence-unit> 7. </persistence>

为了提升软件的执行效率,我们通常选择在某一个范围内缓存 EntityManagerFactory 对象。在 EntityManagerFactory 使用完后,我们需要调 用它的 close 方法来释放相应的资源。获取、使用 EntityManagerFactory 的实 际例子请参考 清单 4 AnimalDAOImpl.java 中的源代码。

获取 EntityManager

要访问 OpenJPA 容器中的实体类,必须首先获得相应的 EntityManager。可 以通过 EntityManagerFactory 对象的 createEntityManager() 方法来获取 EntityManager 对象。获取、使用 EntityManager 的实际例子请参考 清单 4 AnimalDAOImpl.java 中的源代码。

使用Apache OpenJPA开发EJB 3.0应用,第2部分:开发第一个Open JPA应用(7)

时间:2011-08-31 IBM 肖菁

EntityTransaction的启动(提交)

对于 OpenJPA 容器中的持久化对象的创建、修改、删除操作必须在代码中显 式的处理事务,而对于查询操作则不需要在代码中显式的处理事务。JPA 应用中 的事务由 EntityTransaction 接口处理,EntityTransaction 可以直接通过 EntityManager 对象的 getTransaction 方法获得。我们可以调用 EntityTransaction 的 begin(commit) 方法显式的启动(提交)事务。获取、使 用 EntityTransaction 的实际例子请参考 清单 4 AnimalDAOImpl.java 中的源 代码。

Query 接口和 JPQL 查询语言

要查询 EntityManager 中符合条

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号