JPA: Why is adding a table for a specific class optional?

2 answers


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.

+1


source


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.

+1


source







All Articles