According to my understanding in hibernate (please confirm)
1- You have to session.close() if you get it by getSessionFactory().openSession(). 2- No need to session.close() if you get it by getSessionFactory().getCurrentSession(). It is automatically closed after commit().
3- @2 When using getSessionFactory().getCurrentSession(), we have to do all DB activities inside an active transaction so that we can commit() at the end.
4- Hibernate en-queues all save, update, and delete operations and submits them to the database server only after a flush() operation or committing the transaction or closing of the session in which these operations occur.(as per javadoc)
From the above points if I consider 1 & 4, then the following code should work:
Session session =HibernateUtil.getSessionFactory().openSession();AccountDetails ac =newAccountDetails();//perform set operations
session.close();System.out.println("new account stored.");
BUT it is not working i.e. it runs smoothly but does not reflect(store) in database.Why this is so ? When I write the code inside a transaction and commit, then it is stored.
I think I am missing a basic thing. Please clarify.
When you create session using SessionFactory.openSession(), no transaction is created, so your operations are executed outside of transaction context. In order to see your changes, you have to start a new transaction, or perform your operations as a part of ongoing transaction. From documentation:
A typical transaction should use the following idiom: