Spring data CrudRepository and pessimistic lock
<p>I'm using </p>

<ul>
<li>Spring Boot 1.4.2</li>
<li>Spring Data JPA 1.10.5</li>
<li>PostgreSQL 9.5 database</li>
</ul>

<p>I want to have a <code>findOne</code> method with pessimistic lock in my Spring Data repository that is separate from the <code>findOne</code> method that is already provided.</p>

<p>Following <a href="https://stackoverflow.com/a/32315795/1448419">this answer</a> I wrote:</p>

<pre><code>public interface RegistrationRepository extends CrudRepository&lt;Registration, Long&gt; {
    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select r from Registration r where r.id = ?1")
    Registration findOnePessimistic(Long id);
}
</code></pre>

<p>This almost works.</p>

<p>Unfortunately, this does not refresh previous instance of my entity in the entity manager cache. I have two concurrent requests updating the status of my registration</p>

<ul>
<li>the second one waits for the transaction of the first one to commit</li>
<li>the second one does <strong>not</strong> take into account the changes made by the first one.</li>
</ul>

<p>Hence broken behavior.</p>

<p>Any clue why <code>@Lock</code> does not out of the box refresh the entity manager?</p>

<p><em>Update</em></p>

<p>Here is the requested example code:</p>

<pre><code>public interface RegistrationRepository extends CrudRepository&lt;Registration, Long&gt; {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select r from registration_table r where r.id = ?1")
    Registration findOnePessimistic(Long id);

}

public void RegistrationService {

    @Transactional
    public void doSomething(long id){
        // Both threads read the same version of the data 
        Registration registrationQueriedTheFirstTime = registrationRepository.findOne(id);

        // First thread gets the lock, second thread waits for the first thread to have committed
        Registration registration = registrationRepository.findOnePessimistic(id);
        // I need this to have this statement, otherwise, registration.getStatus() contains the value not yet updated by the first thread
        entityManager.refresh(registration);

        registration.setStatus(newStatus);
        registrationRepository.save(registration);
    }
}
</code></pre>