Monday, May 13, 2013

What are Inheritance Stretegies in JPA ?

JPA defines three inheritance strategies namely, SINGLE_TABLE, TABLE_PER_CLASS and JOINED.

Single table inheritance is default, and table per class is optional so all JPA vendors may not support it. JPA also defines mapped super class concept defined through the @MappedSuperClass annotation. A Mapped Super Class is not a persistent class, but allows a common persistable mapping to be defined for its subclasses.

1. Single Table Inheritance
In this inheritance, a single table is used to store all the instances of the entire inheritance hierarchy. The Table will have a column for every attribute of every class in the hierarchy. Discriminator columns identifies which class a particular row belongs.

2. Table Per Class Inheritance
A table is defined for each concrete class in the inheritance hierarchy to store all the attribute of that class and all its super classes.

3. Joined Table
This inheritance replicates the object model into data model. A table is created for each class in the hierarchy to store only the local attributes of that class.

Question - We want to extract common behavior in a super class in JPA entities but we do not want to have table for that super class. How would you achieve this ?
Answer - If we create a normal class as the super class, then as per JPA specifications, the fields for that class are not persisted in the database tables. We need to create a super class extracting the common fields and then annotate that class with @MappedSuperClass in order to persist the fields of that super class in subclass tables. A mapped super class has no separate table defined for it.


No comments:

Post a Comment

Your comment will be published after review from moderator