我有一个设备表,我试图用数据填充。该表有一个自动增量ID和一个制造商列。正确的方式来使用休眠填充数据表
我将所有制造商数据存储在名为manufacturerList的列表中。
然后我遍历整个列表,并为每个条目创建一个具有该条目的新设备对象并存储在变量temp中。在同一个循环中,我尝试使用休眠会话将temp保存到我的表中。
然而,当我运行它,我得到这个错误
java.lang.IllegalStateException:会话/ EntityManager的关闭
什么是实现这个循环,同时使用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();
}
谢谢。
感谢您的快速响应。我已编辑我的帖子,以包括我的会议收购。但是由于我最初没有在代码中使用EntityManager,我可以对现有代码进行修复吗? – 000000000000000000000