I new to hibernate
In my project, i need to handle transactions. How to handle declarative transactions with in two classes
Examples:
//class 1
class A{
createA()
{
insert(A);
}
}
//class 2
class B
{
createB()
{
insert(B);
}
}
//class 3
@Transaction(Exception.class)
class C
{
test()
{
create(A);
create(B);
}
}
As per the above code is there any possibility to handle transactions, in such a way that if the insert in classA success and the insert in the classB fails then the transaction should rollback and remove the record inserted in the table A corresponding to the Class A
please help me with this using declarative transactions....
Thanks in adavace....
Hibernate like anything else supports transaction. So you just need to wrap calls to update() and save() in a transaction.
Example:
Session sess = factory.openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
// your updates to the database
create(A);
create(B);
tx.commit();
}
catch (RuntimeException e) {
if (tx != null) tx.rollback();
throw e; // or display error message
}
finally {
sess.close();
}
And you get your wish. If anything fails between beginTransaction() and commit(), everything is rolled back.
You might have questions about session handling, but that is a different question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.