Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
87 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();
 }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...