两个 EAR 文件,相同的 JPA 实体管理器,相同的事务 =>同一个会话?
假设我有两个应用程序,每个应用程序都有一个单独的 EAR 文件,它们在同一个 JTA 事务中相互调用。如果两者共享相同的实体管理器,它们是否会获得相同的会话,还是每次都会创建新的会话?
Lets say I have two applications, each with an individual EAR file, which call each other within the same JTA Transaction. If both share the same entitymanager, do they get the same session or is it created new each time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
EntityManager(在 JPA 中)或多或少相当于 Session(在 Hibernate 中)。在纯 JPA 应用程序中,您将仅使用 EntityManager。它封装了一个Session。只要 EntityManager 存在,Session 就存在。
没有理由(我认为没有办法)在两个应用程序之间共享 EntityManager,因为它们在不同的 JVM 中运行(至少在我使用过的应用程序服务器上)。您可以做的是共享 EntityManager 设置(称为持久性单元)。您可以通过将实体类和 XML 放入 JAR 中并从两个应用程序中使用它来完成此操作,但具体如何完成可能取决于您的应用程序服务器。它肯定会产生与为第二个应用程序复制类和 XML 完全相同的效果。
将会发生的情况是:两个应用程序中的每一个都将拥有自己的持久性上下文。这意味着,当您在一个应用程序中加载实体时,它不会在另一个应用程序中加载。如果您在应用程序一中加载并修改实体,然后在应用程序二中加载它,应用程序二将看到未修改的实体(除非您有非常奇怪的事务隔离设置并且应用程序一决定刷新实体第一的)。
任何冲突只会在 JTA 事务结束时才会出现。我不知道接下来会发生什么,我认为这取决于你的数据库和事务设置。如果两个应用程序尝试对相同的数据执行不同的操作,则事务可能会回滚。每个应用程序都有自己的数据库连接。它们通过 JTA 事务绑定在一起,因此可以确保两者都提交或都回滚。
An EntityManager (in JPA) is more or less equivalent to a Session (in Hibernate). In a pure JPA application, you would only use the EntityManager. It encapsulates a Session. The Session lives as long as the EntityManager lives.
There is no reason (and I think no way) to share an EntityManager between two applications, as they run in different JVMs (at least on the application servers I've worked with). What you can do is share the EntityManager setup (called a Persistence Unit). You can do that by putting the entity classes and the XML into a JAR and using it from both applications, but how exactly this is done probably depends on your application server. It will definitely have the exact same effect as just duplicating the classes and the XML for the second application.
What will happen is this: Each of the two applications will have its own persistence context. That means, when you load an entity in one application, it will not be loaded in the other. If you load and modify an entity in application one, then load it in application two, application two will see the unmodified entity (except if you have very strange transaction isolation settings and application one decides to flush the entity first).
Any conflicts will only surface at the end of the JTA transaction. I don't know what will happen then, and I think it depends on your database and transaction settings. Probably the transaction will roll back if both applications try to do different things to the same data. Each application will have its own database connection. They are tied together by the JTA transaction, so that is where it is ensured that either both commit or both roll back.