Persisting non-entity class that extends an entity (jpa) - example?
Solution 1
- If you want the concrete classes to be persistent, you have to mark them as
@Entity
(see Abstract Entities and/or Requirements for Entity Classes). - If you want everything to be persisted in one table, use the single table per class hierarchy strategy (see Entity Inheritance Mapping Strategies).
- If you don't want the attributes of the concrete classes to be persisted, mark them all
@Transient
(see Persistent Fields and/or Persistent Properties). - Bonus question: I don't see why they wouldn't as long as you don't mark them
@Transient
.
Solution 2
Read that link again. "An entity class must follow these requirements: * The class must be annotated with the javax.persistence.Entity annotation."
If a class is a non-Entity, then it is a non-Entity so is not persisted as an Entity. Anything persistable has to be marked as such, so mark your subclass as an Entity, and mark fields that you don't want to persist as "transient"
Mike Minicki
Updated on June 05, 2022Comments
-
Mike Minicki almost 2 years
The JPA tutorial states that one can have a non-entity that extends entity class:
Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes. - http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqa.html
Is it possible to persist such structure?
I want to do this:
@Entity abstract class Test { ... } class FirstConcreteTest extends Test { ... } // Non-ntity class SecondConcreteTest extends Test { ... } // Non-entity Test test = new FirstConcreteTest(); em.persist(test);
What I would like it to do is to persist all fields mapped on abstract Test to a common database table for all concrete classes (first and second), leaving all fields of first and second test class unpersisted (these can contain stuff like EJBs, jdbc pools, etc).
And a bonus question. Is it possible to persist abstract property too?
@Entity abstract class Test { @Column @Access(AccessType.PROPERTY) abstract public String getName(); } class SecondConcreteTest extends Test { public String getName() { return "Second Concrete Test"; } }