JPA Native Query for Entity with Inheritance

后端 未结 2 748
萌比男神i
萌比男神i 2020-12-14 22:58

I have an entity class and a subclass based on that entity:

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class A

相关标签:
2条回答
  • 2020-12-14 23:34

    You need to distinguish instances of A from instances of B, using a discriminator. Use one of the following annotations:

    @DiscriminatorValue
    

    http://docs.oracle.com/javaee/5/api/javax/persistence/DiscriminatorValue.html

    @DiscriminatorColumn
    

    https://docs.oracle.com/javaee/5/api/javax/persistence/DiscriminatorColumn.html

    @DiscriminatorFormula
    

    http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#d0e1168

    0 讨论(0)
  • 2020-12-14 23:37

    As you've probably seen, the Hibernate team hasn't put a lot of work into defining how you do this.. the documentation simply states:

    16.1.6. Handling inheritance

    Native SQL queries which query for entities that are mapped as part of an inheritance must include all properties for the baseclass and all its subclasses.

    So if you want to use Native queries it looks like you're stuck doing something like this. Regarding the concern about the subclass B changing, perhaps a slightly less onerous way of implementing this would be to try using LEFT OUTER JOIN syntax on the shared ID property:

    entityManager.createNativeQuery("select a.*, b*, 1 as clazz_, from A a LEFT OUTER JOIN B b on id = a.id where procedure(f)",A.class).getResultList()
    

    That way you'll always get all of the properties from B if you add or remove some.

    0 讨论(0)
提交回复
热议问题