简体   繁体   English

休眠状态下的交易

[英]Transactions in hibernate

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 按照上面的代码,有可能以以下方式处理事务:如果在classA中的插入成功而在classB中的插入失败,则事务应回滚并删除与类A相对应的表A中插入的记录

please help me with this using declarative transactions.... 请使用声明式事务来帮助我。...

Thanks in adavace.... 感谢adavace ...

Hibernate like anything else supports transaction. 像其他任何事物一样,Hibernate支持事务。 So you just need to wrap calls to update() and save() in a transaction. 因此,您只需要在事务中包装对update()和save()的调用即可。

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. 如果beginTransaction()和commit()之间的任何操作失败,则所有操作都会回滚。

You might have questions about session handling, but that is a different question. 您可能对会话处理有疑问,但这是另一个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM