How JPA Transactions Work

The following code runs whenever I want to save any object. Everything seems to be working fine, but I don’t understand how it works!

EntityManager em = getEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();
em.persist( ent );
userTransaction.commit();

The EntityManager above is one instance common to the entire application. After the start of the transaction; I'm just saying em.persist (entity) .. How hibernate knows this belongs to which transaction!

Suppose that in my application there are 10 simultaneous users and all 10 threads executing the above code. Thus, 10 independent transactions are created and completed. But all 10 different organizations I do not associate them with their respective transactions; since JPA can fix it!

Based on the answers; we have below; are we saying that we should have an EntityManager instance for the thread? Will this be a kill on the server! Should we combine these instances? Would this be tantamount to repeating the implementation of the connection pool?

+5
source share
4 answers

It works because you are lucky. Fortunately, this means that commit and begin are called in the correct order - randomly.

You are using a single entity manager instance from multiple threads. This is incorrect because it does not guarantee the security of streaming. Access to a resource level transaction through EntityTransaction is tied to an entity manager instance, not a thread.

, , EntityTransaction . strart , .

hibernate (4.1.4) tx AbstractEntityManageImpl, .

+4

ThreadLocal .

. UserTransaction:

()
.

EntityManager, , , .

, EJB, : http://www.adam-bien.com/roller/abien/entry/is_in_an_ejb_injected

Spring, , : http://static.springsource.org/spring/docs/3.1.1.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight

EntityManagerFactory , EntityManager . JPA EntityManager EntityManager, JNDI , JPA. EntityManager, ; EntityManager , .

+5

, ThreadLocal.

+1

, JTA Hibernate -
, , , bean.
, , bean, EntityManager -
, , , bean bean, , . , . , - .

The transaction object is associated with ThreadLocal, however another thread may resume a suspended transaction, depending on the implementation of your TransactionManager (I'm talking about JBossTransactionManager )

0
source

All Articles