Java 使用无事务的hibernate会话获取对象

Java 使用无事务的hibernate会话获取对象,java,spring,hibernate,spring-transactions,Java,Spring,Hibernate,Spring Transactions,getCurrentSession和openSession之间有什么区别? 我的意思是,使用openSession,我可以在不启动事务和提交事务的情况下从数据库中进行检索 final SessionFactory sf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class) .buildSessionFactory(); Session sessio

getCurrentSession
openSession
之间有什么区别? 我的意思是,使用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()返回绑定到上下文的会话-您不需要关闭。

好的,但是使用openSession()我可以从数据库中检索,而无需开始事务并提交它。这是怎么回事?当我们使用.beginTransaction()时,这意味着我们要维护多个事务(查询)。E.x.您有3个与此事务相关联的查询,如果其中一个查询失败,则另一个查询将被回滚。