Hibernate Transaction Management Comparison

50LV3R :

By referring to T1 and T2, which one is correct practice in creating the hibernate transaction? I have a doubt in choosing one of them. My question is in what situation should I code like T1 or T2.

T1

try{
    currentSession.beginTransaction();

    // assume assume this method is a hql select query
    Person person=personService.findPerson(personId);

    // complex rules that will affect performance
    Health health=healthService.calculateComplexBizRules(personId);

    person.setHealth(health);
    currentSession.commitTransaction();
}catch (Exception e) {
   rollBackTransaction();
   e.printStackTrace();
   throw e;
}

T2

try{
   currentSession.beginTransaction();

   // assume this method is a hql select query
   Person person=personService.findPerson(personId);
   currentSession.commitTransaction();

   // complex rules that will affect performance
   Health health=healthService.calculateComplexBizRules(personId);

   currentSession.beginTransaction();
   currentSession.persist(health);
   Person person=currentSession.merge(person);
   person.setHealth(health);
   currentSession.commitTransaction();
}catch (Exception e) {
   rollBackTransaction();
   e.printStackTrace();
   throw e;
}
Maciej Kowalski :

1) If Optimistic Locking is used, in both cases the Person is retrieved before a complex operation. This means that upon commit if a version of the database is higher than the one originally retrieved you will get OptimisticLockException from which you need to recover (usually by repeating the operation after a merge). This will be the case for T1 and T2 option. You need to decide which one based on a study of how the system behaves here and make appropriate judgement (T2 opens and closes the second transaction which increases the total execution time and does not add any extra benefit in this case).

2) If you need to use Pessimistic Locking, meaning physically lock rows on the database once the complex operation is finished, then you need to go for T1. This might be a bottleneck of course if your Person might be queried many times per second though.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156371&siteId=1