Spring transaction retry

1.9k views Asked by At

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.

0

There are 0 answers