title: Duplicate a collection of entities and persist in Hibernate/JPA
body: <p>I want to duplicate a collection of entities in my database.
  I retreive the collection with:</p>
  
  <pre><code>CategoryHistory chNew = new CategoryHistory();
  CategoryHistory chLast =  (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date = MAX(date)").getSingleResult;
  List&lt;Category&gt; categories = chLast.getCategories();
  chNew.addCategories(categories)// Should be a copy of the categories: OneToMany
  </code></pre>
  
  <p>Now i want to duplicate a list of 'categories' and persist it with EntityManager.
  I'm using JPA/Hibernate.
  <strong>UPDATE</strong></p>
  
  <p>After knowing how to detach my entities, i need to know what to detach:
  current code:</p>
  
  <pre><code>    CategoryHistory chLast =  (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE ch.date=(SELECT MAX(date) from CategoryHistory)").getSingleResult();
      Set&lt;Category&gt; 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);
  </code></pre>
  
  <p>This throws a <code>failed to lazily initialize a collection of role: entities.CategoryHistory.categories, no session or session was closed</code> exception.</p>
  
  <p>I think he wants to lazy load the categories again, as i have them detached. What should i do now?</p>