初学者问题:JPA 的基本插入习惯用法?

发布于 2024-08-25 13:50:34 字数 868 浏览 5 评论 0原文

我的“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜无邪 2024-09-01 13:50:34

您的 employee 在关闭实体管理器后会分离,但没有任何内容禁止访问分离实体的 Id 带注释的属性。 IOW,您的代码是正确的并且可以与 Hibernate 和 EclipseLink 一起使用。也许在 OpenJPA 的 Jira 中搜索现有问题或打开一个新问题。

Your employee becomes detached after closing the entity manager but there is nothing that forbids accessing the Id 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文