使用没有事务的休眠会话获取对象

Get object using hibernate session without transaction

getCurrentSessionopenSession 有什么区别? 我的意思是使用 openSession 我可以在不开始事务并提交的情况下从数据库中检索。

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

但是在getCurrentSession,我必须做session.beginTransaction()session.getTransaction().commit()

.openSession() 总是会打开一个新会话,您必须在完成查询后关闭该会话。而 .getCurrentSession() returns 绑定到上下文的会话 - 您不需要关闭。