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/Update
finally{
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 idiom
Session 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.