bossman
bossman

Reputation: 421

JPA EntityManager default merge behavior

I have two applications that use the same library to work with database. The first application is desktop and the second one is web. So both of them can change the same record at the same time in my database (PostgreSql). The library use this code:

    //it doesnt use em.getTransaction()
em.merge(userAcc);//change useraccount

Can this code cause deadlock? What is default behavior of merge? Does the merge use transaction inside? Actually the order of two merge operations doesnt matter.

Upvotes: 0

Views: 472

Answers (1)

zagyi
zagyi

Reputation: 17518

Relevant quote from the Java Persistence wikibook.

Technically in JPA the EntityManager is in a transaction from the point it is created. So begin is somewhat redundant. Until begin is called, certain operations such as persist, merge, remove cannot be called. Queries can still be performed, and objects that were queried can be changed, although this is somewhat unspecified what will happen to these changes in the JPA spec, normally they will be committed, however it is best to call begin before making any changes to your objects.

So it seems that in this case the behavior of merge() will depend on your persistence provider.

I guess the entity will get updated in an implicit transaction anyway, but I don't think this could cause a deadlock. Worst case scenario is that a concurrent update to the same entity from your two applications will override each other without knowing that. You could prevent that by using optimistic locking.

Upvotes: 1

Related Questions