【发布时间】:2017-01-09 22:00:35
【问题描述】:
我有一个设备表,我正在尝试用数据填充它。该表有一个自增 id 和一个制造商列。
我将所有制造商数据存储在名为manufacturerList 的列表中。
然后我遍历整个列表并为每个条目创建一个带有该条目的新设备对象并存储在变量 temp 中。在同一个循环中,我尝试使用休眠会话将 temp 保存到我的表中。
但是,当我运行它时,我得到了这个错误
java.lang.IllegalStateException: Session/EntityManager 已关闭
在使用休眠时实现此循环的正确方法是什么?
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();
}
谢谢。
【问题讨论】: