JPA: Why is adding a table for a specific class optional?
for the project. I am currently comparing the statistical ORM articles from Hibenate
with my own implementation of the main ORM. Looking through the specs , I found that Single Table
, and Joined subclass
you need to implement, but is not per concrete class
. I tried to find out if there are any obvious flaws, but I cannot find an answer to the question of why joined
it is necessary to maintain, but not concrete
. Does anyone have an answer to this?
thank
source to share
According to the JPA spec, a table for a specific class strategy is optional due to the following disadvantages:
This strategy has the following disadvantages: • It provides poor support for polymorphic relationships. • Typically, queries that target a range in a class hierarchy require SQL UNION queries (or a separate SQL query for each subclass) to be issued.
One particular drawback is that the UNION operator, which is required for polymorphic queries, performs duplicate detection, which slows down the application.
source to share
Imagine the following simple model:
@Entity
@Inheritance(strategy = InheritanceType....)
public class Superclass {
@Id
private Long id;
private String superValue;
}
@Entity
public class Subclass extends Superclass {
private String subValue;
}
Now let's take a look at some queries:
SELECT s FROM Superclass s
This query is translated to SQL for InheritanceType.SINGLE_TABLE
:
SELECT id, dtype, superValue, subValue FROM Superclass
( dtype
is a discriminator column indicating the class of the object)
This query translates to SQL for InheritanceType.JOINED
:
SELECT Superclass.id, dtype, superValue, subValue FROM Superclass
LEFT JOIN Subclass ON Superclass.id = Subclass.id
And finally, for InheritanceType.TABLE_PER_CLASS
:
SELECT id, 'Superclass' AS dtype, superValue, null FROM Superclass
UNION ALL SELECT id, 'Subclass' AS dtype, superValue, subValue FROM Subclass
As you can see, the main drawback is InheritanceType.TABLE_PER_CLASS
: Tables are not normalized and you have to use slow one UNION
. Because this is a "special" table layout and because you have no advantage over it JOINED
, the provider must support it.
source to share