我有一个设备表,我正在尝试用数据填充该表。该表有一个自增 id 和一个制造商列。
我将所有制造商数据存储在名为“manufacturerList”的列表中。
然后,我循环遍历整个列表,并为每个条目创建一个带有该条目的新设备对象,并将其存储在变量 temp 中。在同一循环中,我尝试使用 hibernate session 将 temp 保存到我的表中。
但是,当我运行这个时,我收到此错误
java.lang.IllegalStateException: Session/EntityManager is closed
使用 hibernate 时实现此循环的正确方法是什么?
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Equipment.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
try{
List<String> manufacturerList = new List<String>();
//populate the list here
//...
for (String manufacturer:manufacturerList) {
System.out.println(manufacturer);
Equipment temp = new Equipment(manufacturer);
session.beginTransaction();
session.save(temp);
session.getTransaction().commit();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
factory.close();
}
谢谢。
最佳答案
在循环范围内插入和删除内容时,我相信使用 Session 来确保 session 不会过早关闭的 hibernate 特定实现的正确顺序如下:
SessionFactory factory = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Equipment.class)
.buildSessionFactory();
Session session = factory.getCurrentSession();
try{
List<String> manufacturerList = new List<String>();
//populate the list here
//...
session.beginTransaction();
for (String manufacturer:manufacturerList) {
System.out.println(manufacturer);
Equipment temp = new Equipment(manufacturer);
session.save(temp);
}
session.getTransaction().commit();
} catch (IOException e) {
e.printStackTrace();
} finally {
factory.close();
}
应在将任何内容保存到 session 之前启动事务。在所有保存之后应该提交事务。
改成这样后,程序运行没有错误。
如果有任何我遗漏或可以优化的地方,请随时告诉我。
关于java - 使用 hibernate 用数据填充表的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41557698/