5

I'm dealing with a couple of Entities with Tree like structures that were getting more complicated so I decided to create an abstract class for it so code was a bit more mainainable:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TreeStructure<T extends TreeStructure>
{
    @ManyToOne
    protected  T parent;

    @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
    protected Set<T> children = new HashSet<>();
    //...

Then I have two Entities which extend it:

@Entity(name = "TreeStructureOne")
public class TreeStructureOne extends TreeStructure<TreeStructureOne>
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @JsonProperty("TreeStructureOne_id")
    private long id;

And I basically want the database to be completely unaware of this TreeStructure abstraction and save all of the fields in each Entities tableand expected InheritanceType.TABLE_PER_CLASS to deal with that. But it seems I need to define the Id in the TreeStructure Entity at least or I get:

Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: TreeStructure

And I don't want to add an ID into the abstract class since this makes three tables in the database called: HT_TREE_STRUCTURE, HT_TREE_STRUCTURE_ONE and HT_TREE_STRUCTURE_TWO with one field ID each one.

Is there any solution to that?

  • 3
    Did you try to use `@MappedSuperclass` for the class `TreeStructure` instead of `@Entity` and `@Inheritance`? `@MappedSuperclass` does not have its own Table and is not an Entity. https://docs.oracle.com/javaee/5/api/javax/persistence/MappedSuperclass.html – michaeak Nov 14 '18 at 15:06
  • Nope, I didn't know about it! It passed all the tests I made so exactly what I was looking for. Much thanks! – epsilonmajorquezero Nov 14 '18 at 15:17
  • Great! I just formulated this as an answer – michaeak Nov 15 '18 at 05:04

1 Answers1

3

Since TreeStructure is not an @Entity use only @MappedSuperclass

@MappedSuperclass
public abstract class TreeStructure<T extends TreeStructure> {

instead of @Entity and @Inheritance for the parent class.

You can find @MappedSuperclass in the Oracle JEE API documentation.

michaeak
  • 1,548
  • 1
  • 12
  • 23