I'm trying to write a JUnit test on pessimistic write. My thought is to execute this method within one transaction while running it again in another transaction and trying to modify the element that's returned from the method in the first transaction. I would expect an exception/timeout because the first call should lock the row. I have done something similar to this but the element is modified by the second transaction (testNewTrans method) without hesitation. Is there somewhere I did wrong?
public interface RequestRepository extends CrudRepository<Object, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("select ... ")
List<Object> findABC(Pageable pageable);
}
in junit
@RunWith(SpringRunner.class)
@DataJpaTest
@TransactionConfiguration(defaultRollback = true)
public class RepositoryTest {
@Configuration
@ComponentScan("test.package")
@ContextConfiguration
public static class SpringConfig {
}
@Test
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void testLock() throws InterruptedException {
List<Object> requests1 = requestRepository.findABC(new PageRequest(0, 2));
test22.testNewTrans(); // return empty list
}
in new class
@Component
public class Test22 {
private final RequestRepository requestRepository;
public Test22(RequestRepository requestRepository) {
this.requestRepository = requestRepository;
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
private void testNewTrans() {
List<Object> requests2 = requestRepository.findABC(new PageRequest(0, 2));
Object aa = requests2.get(0);
System.out.println("=============>" + aa);
aa.setSomething("abc");
}
}