【发布时间】:2019-07-22 02:39:41
【问题描述】:
我是 hibernate 的初学者,我只想知道对象是仅与 session.close() 分离还是与 session.getTransaction().commit() 分离。因为我无法从另一个事务中更新对象,所以它会抛出一个例外。
这是我的代码。
package com.steve.hibernate.HibernateDemo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.steve.hibernate.HibernateDemo.entity.Student;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().addAnnotatedClass(Student.class)
.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Student student = session.get(Student.class, 17);
System.out.println(student);
session.getTransaction().commit();
session.beginTransaction();
student.setFirstName("BOOM");
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
}
输出:
Hibernate: select student0_.id as id1_0_0_, student0_.email as email2_0_0_, student0_.first_name as first_na3_0_0_, student0_.last_name as last_nam4_0_0_ from student student0_ where student0_.id=?
Student [id=17, firstName=BOOM, lastName=asd, email=asd@gmail.com]
Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:357)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:138)
at org.hibernate.internal.AbstractSharedSessionContract.beginTransaction(AbstractSharedSessionContract.java:449)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:350)
at com.sun.proxy.$Proxy33.beginTransaction(Unknown Source)
at com.steve.hibernate.HibernateDemo.App.main(App.java:25)
如果对象可以与 session.close() 分离,为什么我不能更新持久对象的值?
【问题讨论】:
-
用户指南中对此进行了说明:docs.jboss.org/hibernate/orm/current/userguide/html_single/…。 前两个实现提供了一个会话 - 一个数据库事务编程模型。这也被称为 session-per-request。 Hibernate 会话的开始和结束由数据库事务的持续时间定义。
-
@JBNizet 那么 OP 需要做什么呢?再次致电
sessionFactory.getCurrentSession()?还有什么?