gpt4 book ai didi

java - 为什么即使事务已提交,EntityManager 也会关闭?

转载 作者:行者123 更新时间:2023-11-30 03:35:16 25 4
gpt4 key购买 nike

我正在使用 JPA 和 Hibernate 进行一些简单的测试,并且碰巧在我不希望的情况下关闭了 EntityManager。

这是我的测试主要:

public class TestMain {
public static void main(String[] args) {
DBResourcesManager.initPeristence();
List<Event> allEvents = EventDao.findAllEventsA();
Event e1 = new Event("Event", new Date());
EventDao.store(e1);
DBResourcesManager.shutdown();
}
}

数据库助手:

public class DBResourcesManager {

private static EntityManager entityManager;
private static EntityManagerFactory entityManagerFactory;

public static void initPeristence() {
entityManagerFactory = Persistence.createEntityManagerFactory("pu");
entityManager = entityManagerFactory.createEntityManager();
}

public static EntityManager getEntityManager() {
return entityManager;
}

public static void shutdown() {
entityManager.close();
entityManagerFactory.close();
}
}

实体和对应的DAO:

public class Event {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;

@Temporal(TemporalType.DATE)
private Date date;
/*...*/
}

public class EventDao {
public static void store(Event e) {
EntityManager em = DBResourcesManager.getEntityManager();
EntityTransaction t = em.getTransaction();
t.begin();
em.persist(e);
t.commit();
em.close();
}

public static List<Event> findAllEventsA() {
EntityManager em = DBResourcesManager.getEntityManager();
EntityTransaction t = em.getTransaction();
t.begin();
List<Event> events = em.createQuery("from Event", Event.class)
.getResultList();
t.commit();
return events;
}
}

在商店中,开始交易时,我得到以下信息:

Exception in thread "main" java.lang.IllegalStateException: EntityManager is closed

关闭方法未执行。为什么实体管理器被关闭?

为了完整起见,这里是 persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pu">
<class>com.lh.hibernateexample.Event</class>
<properties>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/myfirsthibernatedb" />
<property name="hibernate.connection.username" value="XXXXXXXX" />
<property name="hibernate.connection.password" value="XXXXXXXX" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.archive.autodetection" value="class" />
</properties>
</persistence-unit>
</persistence>

最佳答案

您在存储方法中关闭实体管理器,然后尝试在关闭方法中再次关闭它。

在 DAO 中使用静态方法很奇怪。

关于java - 为什么即使事务已提交,EntityManager 也会关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28129954/

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