Skip to content

Commit

Permalink
doc: how to lock with Panache
Browse files Browse the repository at this point in the history
How to implement a JPA lock with Panache
  • Loading branch information
loicmathieu committed Jun 11, 2019
1 parent e6b47d6 commit c4f29a9
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
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 don't provides direct support to lock the database, but you can easily do it by injecting the `EntityManager` in your entity (or `PanacheRepistory` ) and creating a specific method that will use the entity manager to lock the entity after retrieval.

The following exemple contains a `findByIdForUpdate` method that find the entity by primary key then lock it. The lock will generate a `SELECT ... FOR UPDATE` query (the same principle can be used for other kind 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 carreful that locks are released when the transaction finish, so the method that generate the lock query must be annotated by the `@Transactional` annotation.

There is an ongoing discussion for a direct support to lock management inside Panache, you access it on the github issue link:https://github.com/quarkusio/quarkus/issues/2744[#2744]: and vote for it (+1) if needed.

== 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 c4f29a9

Please sign in to comment.