gpt4 book ai didi

java - session.getTransaction().commit() 是否在 hibernate 中关闭 session ?

转载 作者:行者123 更新时间:2023-12-02 02:47:24 27 4
gpt4 key购买 nike

我是 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() 中分离出来,为什么我无法更新持久对象的值?

最佳答案

您无需初始化另一笔交易。获取学生后,请尝试在提交之前更新它,因为除非刷新模式设置为手动,否则事务可能会被刷新,就是这种情况。尝试在单个事务中执行此操作。

关于java - session.getTransaction().commit() 是否在 hibernate 中关闭 session ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57135448/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com