ppatidar
ppatidar

Reputation: 177

JPA Lock Mode behaviour

I have a java method running in transaction where I read an Oracle database table using following JPA query and then insert a new record in the same table using the result from the following query. I want to understand how lock mode PESSIMISTIC_WRITE will work in this scenario. Will the whole table be locked when THE following query is executed, blocking other reads from this table until my method commits the transaction after insert?

    @NamedQuery(name = "findByMaxSeqForGivenOrd", query = "select ar from Remark ar 
where ar.sequenceNumber = (select max(ar1.remarkId.sequenceNumber) from Remark ar1 
where ar1.remarkId.orderNum = ar.remarkId.orderNum 
AND ar1.remarkId.orderNum=:orderNum)", 
lockMode=LockModeType.PESSIMISTIC_WRITE, 
hints = @QueryHint( name = "javax.persistence.lock.timeout", value = 
"3000"))

Upvotes: 3

Views: 1895

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26522

If you use LockModeType.PESSIMISTIC_WRITE on a query, then you would end up adding an equivalent of Serializable isolation level on oracle db.

On the database level only the rows corresponding to the result entities will be locked with few things to consider:

  • Entity relationships for which the locked entity contains the foreign key will also be locked, but not the state of the referenced entities (unless those entities are explicitly locked).

  • ElementCollections and relationships for which the entity does not containd the foreigh key: @OneToMany, @ManyToMany; will not be locked by default.

  • ElementCollections and and relationships owned by the entity that are contained in the join tables will be locked if the 'javax.persistence.lock.scope' property is specified with a value PessimisticLockScope.EXTENDED.

Upvotes: 1

Related Questions