Search code examples
javaspringhibernatespring-transactions

Get object using hibernate session without transaction


What are differences between getCurrentSession and openSession? I mean using openSession I could make retrieve from the DB without beginning the transaction and committing it.

final SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class)
                .buildSessionFactory();
Session session = sf.openSession();

Student student = session.get(Student.class, 1);
System.out.println(student);

session.close();
sf.close();

But in getCurrentSession, I have to do session.beginTransaction() and session.getTransaction().commit()


Solution

  • .openSession() always opens a new session that you have to close once you are done with the queries. whereas .getCurrentSession() returns a session bound to a context - you don't need to close.