Transaction Management
In my code I am updating two table, one after the other.
update(table1_details);
update(table2_details);
So if the update fails in table1 , table2 should not be updated or should be rolled back.
How to handle this situation. I know I have to use transaction. Ca开发者_StackOverflown some one help with code !!! I am using Java with spring and hibernate .
The question is a bit broad and there are several ways to implement this but I would:
- Use Spring to inject Hibernate
SessionFactory
into DAOs objects. - Use Spring to inject DAOs in a service object and call them inside a business method.
- Use Spring declarative transaction management at the business method level (either with Spring AOP or
@Transactional
).
Something like this:
@Transactional
public void doSomething() {
dao1.foo();
dao2.bar();
}
For more details on the configuration, check the Chapter 9. Transaction management of the Spring documentation.
I can't recall the correct api, but something like this:
Transaction tx = em.getTransaction();
tx.begin();
try {
update1(); update2();
}
catch(Exception e) {
failed = true
}
finally {
if( !failed ) tx.commit();
else tx.rollbacl();
}
精彩评论