can begin transaction in hibernate called while commiting/rollback

来源:互联网 发布:js获取跳转前的url 编辑:程序博客网 时间:2024/05/29 17:26

Will the below code works fine or do I need to begin transaction before doing work.

Session session = SessionFactory.openSession();//do some work like session.save/Updatefinally{    session.beginTransaction().commit();}

No. Of course the code being part of the transaction must be between the begin and the commit of the transaction.

Here(s what the documentation says:

The session/transaction handling idiom looks like this:

// Non-managed environment idiomSession sess = factory.openSession();Transaction tx = null;try {    tx = sess.beginTransaction();    // do some work    ...    tx.commit();}catch (RuntimeException e) {    if (tx != null) tx.rollback();    throw e; // or display error message}finally {    sess.close();}

No you need to manage transaction, commit for getting immediate effect and any exceptions thrown by Hibernate are FATAL, you have to roll back the transaction and close the current session.

0 0