I am using spring with JPA Repository.
I am trying to get the sequence number from one table and after some operations, updating the same.
I have to write the test code for multi thread transaction in this scenario, i.e. If a request get the sequence number from select query then it can not be accessible by another request till first request completion. So i have searched over internet and find a solution for JPA i.e.
@Lock(LockModeType.PESSIMISTIC_WRITE)
I have implement above statement with my repository function i.e.
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query(value = "from FileNumberSequence where headBasicId = :headBasicId and headPrimaryId= :headPrimaryId and year = :year")
public FileNumberSequence getFileNumberSequence(@Param("headBasicId") Long headBasicId,
@Param("headPrimaryId") Long headPrimaryId, @Param("year") Integer year);
May be above code will work fine in production environment but I have to write test code for the same.
So I have test it with two transactions, i.e.
TransactionStatus status1 = transactionManager.getTransaction(new DefaultTransactionDefinition());
this.mockMvc
.perform(MockMvcRequestBuilders.post("/file").contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(this.fileDTO)))
.andExpect(MockMvcResultMatchers.status().isOk());
transactionManager.commit(status1);
DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
TransactionStatus status2 = transactionManager.getTransaction(transactionDefinition);
this.mockMvc
.perform(MockMvcRequestBuilders.post("/file").contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(this.fileDTO)))
.andExpect(MockMvcResultMatchers.status().isOk());
transactionManager.commit(status2);
In above scenario, the first request, fire the select query but after that it is not working any more.
Please provide a solution for the same. If you know any other way to write the test code for the same, please explain.