Monday, November 25, 2013

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 = new AccountDetails();  
//perform set operations  
session.save(ac);  
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.
share|improve this question
 
I think you missed Transactions here! ( or somewhere in your configurations) see the link for step by step guidlaliluna.de/articles/java-persistence-hibernate/… –  Morteza Adi Apr 29 at 10:18 
 
Can you share the javadoc link from point 4? –  dcernahoschi Apr 29 at 10:20
add comment

2 Answers

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:
Session sess = factory.openSession();
 Transaction tx;
 try {
     tx = sess.beginTransaction();
     //do some work
     ...
     tx.commit();
 }
 catch (Exception e) {
     if (tx!=null) tx.rollback();
     throw e;
 }
 finally {
     sess.close();
 }
share|improve this answer
add comment

No comments: