Sunday, February 7, 2016

Spring data JPA Pessimistic lock

If you want to lock a database record to execute certain business logic and do not want any other thread to update the same then do the following -
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import javax.persistence.LockModeType;

public interface PersonRepository extends CrudRepository {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select p from Person p where p.id = :id")
    Person findOneAndLock(@Param("id") int id);
}
In this example Person is an entity and I want to lock a Person record based on id. The service layer method must be in transaction to use this method.

3 comments:

  1. How we can test above case by junit?

    ReplyDelete
  2. @Nitin One option is write tests integrated with database as essential you want to test if all the annotations used are matching with database schema. Use two threads in which first one takes the lock and wait. Second thread then tries and it will fail so assert for the exception.

    ReplyDelete
  3. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

    ReplyDelete