JPA PessimisticLockScope.NORMAL and locking “relationships”

Tags: , , , ,



I am studying JPA Documentation and encountered the following lines:

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). Element collections and
relationships for which the entity does not contain the foreign key
(such as relationships that are mapped to join tables or
unidirectional one-to-many relationships for which the target entity
contains the foreign key) will not be locked by default.

it’s from here (PessimisticLockScope.NORMAL)

I wonder how to interpret these lines. If PessimisticLockScope is set to EXTENDED then rows in join tables are also locked (but not related entities themselves), so when using NORMAL value what will be locked? For sure entity row (or rows if inheritance strategy is JOINED or TABLE_PER_CLASS or if has a SecondaryTable), but what means “entity relationships”:

Entity relationships for which the locked entity contains the foreign
key will also be locked

in the context of PessimisticLockScope.NORMAL?

Answer

Entity relationships are mapped to database FK associations.

The PessimisticLockScope.NORMAL will issue a quite aggressive database exclusive locking on:

  • the entity dissociated table rows
  • in a joined table inheritance structure both the base table and the subclass table are going to be locked
  • all @ManyToOne and @OneToOne associated table rows that have an actual FK relationship (e.g. the side with @JoinColumn). But it means you can’t alter the FK info, meaning you can’t set it to null or to any other different value. So only the FK column value is locked not the other table associated FK row.

The @OneToMany, @ManyToMany and non-owning @OneToOne and @ManyToOne associations are not going to be locked because these associations have only an Object-Oriented equivalent and the locking happens solely at the database level.

The PessimisticLockScope.EXTENDED will expand to the @OneToMany and @ManyToMany associations too. But again, this only applies to FK column values not to whole rows. So this locking will prevent adding/removing elements to/from @OneToMany/@ManyToMany associations. It doesn’t prevent the contained elements from being updated. For that, you will have to lock each contained entity.



Source: stackoverflow