Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good inheritance strategy with Hibernate and JPA?

I have this situation:

I have an entity, Person, that contains all personal details of a person, like birth date, street address, municipality ecc ecc. And I have an entity ClubMember that describe a member of a club and contains some field like: registration date, type of member, credit, ecc ecc

So, a ClubMember is a Person, and I think is correct describe this with a inheritance: ClubMember extends Person, but, what type of strategy?

I would obtain two table in database, Person and ClubMember, with ClubMember that contain id_person like an @OneToOne relationship, but keep the inheritance between entities; is this possible (and is correct)?

JOINED is the strategy closest to my target, but I lose the ID field of table ClubMember, in fact ID become the ID of table Person...

like image 390
blow Avatar asked Jul 31 '10 23:07

blow


People also ask

What are inheritance strategies in JPA?

Inheritance Strategies Inheritance is the core concept of object oriented language, therefore we can use inheritance relationships or strategies between entities. JPA support three types of inheritance strategies such as SINGLE_TABLE, JOINED_TABLE, and TABLE_PER_CONCRETE_CLASS.

Which of the following are inheritance strategies in Hibernate?

There are three inheritance mapping strategies defined in the hibernate: Table Per Hierarchy. Table Per Concrete class. Table Per Subclass.

How many inheritance mapping strategies are there in JPA?

JPA and Hibernate support 4 inheritance strategies which map the domain objects to different table structures.


1 Answers

Blow, you should keep performance issues when choosing some kind of inheritance strategy. Here you can see a good insight about available inheritance strategies. Do not forget a inheritance can be re-writen as a association as follows

instead of

public class A {}

public class B extends A {}

you can use

public class B {

    private A a;

}

Or you can use MapedSuperClass To map all of your inherited properties whitout using any Hibernate/JPA inheritance strategy. See here

Keep in mind when using default JPA/Hibernate annotations, Hibernate always fetch all of subclasses. If you have a single hierarchy, prefer To use Single Table Inheritance strategy. Joined strategy is better designed when you have a complex hierarchy but it suffers due To performance issues when querying for any entity.

like image 86
Arthur Ronald Avatar answered Sep 26 '22 02:09

Arthur Ronald