0

Environment :

Spring 4.0.3

JPA : 2.1 with underlying implementation of Hibernate 4.3.5.Final

This is the pseudo code from my application.

@Transactional
doRegistration() {

    //user insert
    entityManager.persist(userObj); 

    //user permission insert
    entityManager.persist(permissionObj);   

    //find the max id from address table
    maxId = entityManager.findAddressMaxId(userObj.userid)

    id = maxId + 1;
    //other business logics goes here

    //insert user address with id
    entityManager.persist(addressObj);
}

There are multiple such code blocks in my system which do a max +1 for the new id.

There are cases in which a race condition can happen. In those cases the addressObj insert can fail due to primary key violation.

I tired with @GeneratedValue, the problem in that case is, there is one external system which do this same registration to these tables. In addition to that there are some cases in which my legacy database use char data type for id.

It is least preferred to add some code level changes to execute again the address insert on an exception case.

Is there any option in org.springframework.transaction.annotation.Transactional which can make the method to attempt again with out a roll back?

Other thoughts are also most welcome.

Sam
  • 554
  • 1
  • 12
  • 23
  • Is synchronizing an option? – reto Jun 18 '15 at 05:26
  • There is one external system operating on these same tables so synchronizing will not help. Thanks for the comment – Sam Jun 18 '15 at 05:30
  • Ah I understand. Did you see http://stackoverflow.com/a/3165406/133645 ? – reto Jun 18 '15 at 05:33
  • Intercepting the transaction with AOP... This is one option I can try, however a solution from Spring is the first preference. – Sam Jun 18 '15 at 05:48
  • 2
    You can use [Spring Retry](https://github.com/spring-projects/spring-retry) for that. However doing updates yourself is painful, you might want to use a sequence or table containing counters instead that way you can use transactions to limit access. – M. Deinum Jun 18 '15 at 06:20

0 Answers0