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);
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.
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.)
精彩评论