Skip to content

Commit

Permalink
Merge pull request quarkusio#2788 from loicmathieu/feat/document_jpa_…
Browse files Browse the repository at this point in the history
…lock

doc: how to lock with Panache
  • Loading branch information
FroMage authored Jun 19, 2019
2 parents 8b733eb + bfc459b commit 5d03b07
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions docs/src/main/asciidoc/hibernate-orm-panache-guide.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,37 @@ Make sure to wrap methods modifying your database (e.g. `entity.persist()`) with
CDI bean method `@Transactional` will do that for you and make that method a transaction boundary. We recommend doing
so at your application entry point boundaries like your REST endpoint controllers.

== Lock management

Panache does not provide direct support for database locking, but you can do it by injecting the `EntityManager` in your entity (or `PanacheRepository`) and creating a specific method that will use the entity manager to lock the entity after retrieval. The entity manager can also be retrieved via `Panache.getEntityManager()`.

The following example contains a `findByIdForUpdate` method that finds the entity by primary key then locks it. The lock will generate a `SELECT ... FOR UPDATE` query (the same principle can be used for other kinds of `find*` methods):

[source,java]
--
@Entity
public class Person extends PanacheEntity {
public String name;
public LocalDate birth;
public Status status;

// inject the EntityManager inside the entity
@Inject
EntityManager entityManager;

public static Person findByIfForUpdate(Long id){
Person person = findById(id);
//lock with the PESSIMISTIC_WRITE mode type : this will generate a SELECT ... FOR UPDATE query
entityManager.lock(person, LockModeType.PESSIMISTIC_WRITE);
return person;
}
}
--

This will generate two select queries: one to retrieve the entity and the second to lock it. Be careful that locks are released when the transaction ends, so the method that invokes the lock query must be annotated with the `@Transactional` annotation.

We are currently evaluating adding support for lock management inside Panache. If you are interested, please visit our github issue link:https://github.com/quarkusio/quarkus/issues/2744[#2744] and contribute to the discussion.

== Custom IDs

IDs are often a touchy subject, and not everyone's up for letting them handled by the framework, once again we
Expand Down

0 comments on commit 5d03b07

Please sign in to comment.