我想在我的数据库中复制一组实体.
我用以下方式检索了这个系列:
CategoryHistory chNew = new CategoryHistory();
CategoryHistory chLast = (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date = MAX(date)").getSingleResult;
List categories = chLast.getCategories();
chNew.addCategories(categories)// Should be a copy of the categories: OneToMany
现在我想复制一个’类别’列表并用EntityManager保存它.
我正在使用JPA / Hibernate.
UPDATE
在知道如何分离我的实体之后,我需要知道要分离的内容:
当前代码:
CategoryHistory chLast = (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date=(SELECT MAX(date) from CategoryHistory)").getSingleResult();
Set categories =chLast.getCategories();
//detach
org.hibernate.Session session = ((org.hibernate.ejb.EntityManagerImpl) em.getDelegate()).getSession();
session.evict(chLast);//detaches also its child-entities?
//set the realations
chNew.setCategories(categories);
for (Category category : categories) {
category.setCategoryHistory(chNew);
}
//set now create date
chNew.setDate(Calendar.getInstance().getTime());
//persist
em.persist(chNew);
这会抛出一个未能懒惰地初始化角色集合:entities.CategoryHistory.categories,没有会话或会话被关闭的异常.
我认为他想再懒得加载类别,因为我让它们分离了.我现在应该怎么做?