初学者问题:JPA 的基本插入习惯用法?
我的“HelloJPA”代码(如下)尝试将 Employee 存储在数据存储中。但是,在提交(资源本地)事务后任何读取持久对象的尝试都会得到“IllegalStateException”:
Employee employee = ...
EntityManagerFactory factory =
Persistence.createEntityManagerFactory( "HelloJPA", System.getProperties() );
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
try {
transaction.begin();
manager.persist( employee );
transaction.commit();
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
manager.close();
}
System.out.println("Employee id == " + employee.getId() ); //<< IllegalStateException
好吧,我猜,经理占有了我新分配的员工对象,并且一旦我提交了事务,它就变得不可用。但是,实现这个简单操作的常见习惯是什么,即将一个对象一直写入数据存储,同时仍保持对其的只读访问权限?文档(教程或 API 参考)没有具体解决这个问题,而且我发现使用资源本地事务的代码示例似乎从未在提交后尝试读取对象......但肯定有一个简单的方法去做吗?
预先感谢您对此的任何帮助/指示!
My "HelloJPA" code (below) tries to store an Employee in a datastore. However, any attempt to read the persisted object after committing the (resource local) transaction is rewarded with an "IllegalStateException":
Employee employee = ...
EntityManagerFactory factory =
Persistence.createEntityManagerFactory( "HelloJPA", System.getProperties() );
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
try {
transaction.begin();
manager.persist( employee );
transaction.commit();
} finally {
if (transaction.isActive()) {
transaction.rollback();
}
manager.close();
}
System.out.println("Employee id == " + employee.getId() ); //<< IllegalStateException
OK, I guess, the manager took possession of my new-allocated employee object and it became unavailable once I committed the transaction. But then, what's the common idiom to implement this simple operation, i.e., writing an object all the way to the datastore while still keeping read-only access to it? The documentation (tutorials or API references) doesn't address this specifically, and the code samples I've found that use resource local transactions never seem to try to read the object after committing ... But surely there must be a trivially simple way to do it??
Thanks in advance for any help/pointers on this!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
employee
在关闭实体管理器后会分离,但没有任何内容禁止访问分离实体的Id
带注释的属性。 IOW,您的代码是正确的并且可以与 Hibernate 和 EclipseLink 一起使用。也许在 OpenJPA 的 Jira 中搜索现有问题或打开一个新问题。Your
employee
becomes detached after closing the entity manager but there is nothing that forbids accessing theId
annotated property of a detached entity. IOW, your code is correct and works with Hibernate and EclipseLink. Maybe search in OpenJPA's Jira for an existing issue or open a new one.