title: How do I persist a list of subtypes with JPA 2.0?
body: <p>I have a manager class with a list of visitable elements that I would like to persist in a database using JPA/Hibernate:</p>
  
  <pre><code>@Entity
  class Elements {
    void accept(Visitor v) {...}
    @? List&lt;Visitable&gt; elements;  // or List&lt;AbstractElement&gt;
  }
  
  @? class AbstractElement implements Visitable {}
  
  @Entity class Element1 extends AbstractElement {}
  @Entity class Element2 extends AbstractElement {}
  
  class ElementDAO {
    void saveElements(Elements e, EntityManager em) {
      em.persist(e);
    }
  }
  </code></pre>
  
  <p>I have tried multiple approaches.  I have tried to mark AbstractElement as @MappedSuperclass, but then Hibernate cannot figure out the correct Visitable type, and won't let me mark it with @OneToMany(targetEntity=AbstractElement.class).  I have tried changing the List to contain AbstractElement but Hibernate complains that it cannot instantiate an abstract class.  I have also tried using TABLE_PER_CLASS inheritance strategy on the AbstractElement class and get the same 'cannot instantiate' error.</p>
  
  <p>Is there anything I can do to solve this issue?  Is this doable at all?</p>
  
  <p>I've searched many similar questions on this site dealing with jpa and inheritance, but none of the suggestions have worked.</p>
  
  <p>Update:
  So it looks like the issue was not with the method of inheritance or abstract classes per-se, but with the fact that I was trying to use EntityManager::merge() instead of EntityManager::persist().  I believe that has to do with the fact that merge makes a copy of the entity.</p>
  
  <p>So in light of this new knowledge, do I just have to acknowledge that merge cannot work with a collection of a abstract classes?  Or is there some way to add a copy-constructor that hibernate can call?</p>