According to my understanding in hibernate (please confirm)
1- You have to session.close()
if you get it by getSessionFactory().openSession()
I was also trying to understand the point: save() can perform Insert operation outside transaction boundary so I did something like this
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
session.save(user);
session.close();
But data not inserted in database.So I again tried this and now it worked for me and data inserted sucessfully:
in configuration file:
<property name="connection.autocommit">true</property>
and in java code:
SessionFactory factory = new Configuration().configure()
.buildSessionFactory();
Session session = factory.openSession();
session.save(user);
session.flush();
session.close();
session.close() is only responsible to close the session https://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/Session.html#close()
how to work with hibernate session: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-basics
// 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();
}
As it wrote in the documentation: a much more flexible solution is Hibernate's built-in "current session" context management:
// Non-managed environment idiom with getCurrentSession()
try {
factory.getCurrentSession().beginTransaction();
// do some work
...
factory.getCurrentSession().getTransaction().commit();
}
catch (RuntimeException e) {
factory.getCurrentSession().getTransaction().rollback();
throw e; // or display error message
}
if there is DB manipulation operation then it should be in transaction
if you call session.save(object)
hibernate create bellow query only .
select hibernate_sequence.nextval from dual
so right code is here
Transaction t=session.beginTransaction();
session.save(obect);
t.commit(); should not forgot to commit.
session.close();