0

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

m.y.m
  • 347
  • 4
  • 27

1 Answers1

1

.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.

vishal pathode
  • 138
  • 1
  • 7
  • Okay but with openSession() I could make retrieve from the DB without beginning the transaction and committing it. How it that? – m.y.m Sep 26 '19 at 06:42
  • when we use .beginTransaction() that means we are maintaining our multiple transactions(queries). E.x. you have 3 queries associated with this transaction and if one of them fails then other will get roll-backed. – vishal pathode Sep 26 '19 at 10:02