Bilal Dekar
Bilal Dekar

Reputation: 3986

Inheritance of java entities 3 level

i want to create 3 levels inheritane in java entities

Example : A <- B <- C

Where B inherit from A and C inherit from B

I tried to use @MappedSuperclass in class A :

@MappedSuperclass
public class A {

}

And entity B extends A :

@Entity
public class B extends A {

}

the entity B is mapped to a database table with A fields and B fields

How can i add a third level C that extends B and A, i tried the following code but Entity C is not mapped to a table :

@Entity
public class C extends B {

}

Upvotes: 0

Views: 167

Answers (1)

zlaval
zlaval

Reputation: 2047

You mean inherritance in JPA. It is not as easy as plain object inherritance. Those entities are mappings of database's tables, so inherriting them means that the tables in database are related to each others. There are multiple types of inherritance.

@MappedSuperclass is one of those strategy. When use it, all fields from the parent and the children class is mapped into one table. You can use multi level @MappedSuperclass, but those parents wont be mapped to tables.

It maybe resolve your problem, if you create a class with content of B which extends from A and mark it with @MappedSuperclass too, then C and B as concrete entities inherrit from it. So B becomes an empty class and C stay as is but different parent.

You can use another strategies too.

For example you can annotate a concrete entity class with @Inheritance(strategy = InheritanceType.SINGLE_TABLE), then any entities inherrited from these annotated class will mapped into the same table.

@Inheritance(strategy = InheritanceType.JOINED) creates separate tables to children as well as the parents, and joining them with the ids.

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) will create a separate table to all children and any contains all props from the entity and parent.

Upvotes: 1

Related Questions