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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With