tags:

views:

381

answers:

2

Is it possible to use PESIMISTIC lock option using Spring JpaTemplate methods?

I know that PESIMISTIC lock can be performed using EntityManager's methods e.g.

Account acc = em.find(Account.class, 123);

em.lock(acc, PESIMISTIC);

+1  A: 

There's nothing specifically on JpaTemplate for this, but if you need access to it, you can use JpaTemplate.execute(), which takes a callback which is supplied with the EntityManager, and you can do anything you like within that callback.

A better solution, depending on your situation, might be to use Spring's transaction layer. If you annotate your DAO with @Transactional (see previous link), the JpaTransactionManager should manage entity locking for you, depending on the isolation attribute of the @Transactional attribute.

skaffman
I wanted to use isolation attribute on the method annotation level but JPA seems to not support other than DEFAULT isolation levels:`org.springframework.transaction.InvalidIsolationLevelException: Standard JPA does not support custom isolation levels - use a special JpaDialect for your JPA implementation`
Łukasz Koniecki
It's common for people to find that plain JPA is not good enough, and they need to use proprietary extensions to get the job done. What JPA implementation are you using?
skaffman
We are using EclipseLink
Łukasz Koniecki
A: 

Depending on your default isolation level, a find followed by a lock can leave you open to consistency issues. Also, the code you posted will probably turn into two database round-trips instead of just one. It'd be preferable to do:

  em.find(Account.class, 123, PESSIMISTIC);

Or, if you're using JPA 1:

  Account acc = em.getReference(Account.class, 123);
  em.lock(acc, PESSIMISTIC);

(This isn't an answer to the question per se, but rather a comment about the OP's code. Sadly, Stack Overflow comments don't seem to support formatting.)

Patrick Linskey