With JPA, we can use manually OPTIMISTIC or PESSIMISTIC locking to handle entity changes in transactions.
I wonder how JPA handles locking if we don’t specify one of these 2 modes ?
No locking mode is used?
If we don’t define an explicit locking mode, can the database integrity be lost?
Thanks
I’ve scanned through section 3.4.4 Lock Modes of the Java Persistence API 2.0 Final Release specification and while I couldn’t find anything specific (it doesn’t state that this is the default or anything like that) there is a footnote which says the following.
The section is about the kinds of
LockModeTypevalues available and their usages and describes which methods takes an argument of this kind and whatnot.So, as it said
LockModeType.NONEis default for annotations (JPA, annotations left and right) I guess when you useEntityManager.find(Class, Object)the defaultLockModeTypeis used.There are some other, subtle, hints to reinforce this. Section 3.1.1 EntityManager interface.
It makes sense. For example if you use MySQL as your database and your database engine of choice is InnoDB then (by default) your tables will use
REPEATABLE READ, if you use some other RDBMS or other database engines this could change.Right now I’m not exactly sure that isolation levels has anything to do with JPA lock modes (although it seems that way), but my point is that different database systems differ so JPA can’t decide for you (at least according to the specification) what lock mode to use by default, so it’ll use
LockModeType.NONEif you don’t instruct it otherwise.I’ve also found an article regarding isolation levels and lock modes, you might want to read it.
Oh, and to answer your last question.
It depends, but if you have concurrent transactions then the answer is probably yes.