Java /JPA | Query with specified inherited type

后端 未结 4 1839
野的像风
野的像风 2020-12-10 13:23

I am building a query on a generic table \"Sample\" and I have several types which inherit from this table \"SampleOne\", \"SampleTwo\". I require a query like :

         


        
相关标签:
4条回答
  • 2020-12-10 13:48

    You still have to be carefull in Hibernate 4.3.7, because there is still an issue with the implementation of TYPE(), for example:

    from SpoForeignPilot sfp where TYPE(sfp.partDocument) = :type
    

    This query doesn't work as it incorrectly checks the type of SpoForeignPilot and not the type of the document.

    You can workaround this issue by doing something like this:

    select sfp from SpoForeignPilot sfp join sfp.partDocument doc where TYPE(doc) = :type
    
    0 讨论(0)
  • 2020-12-10 13:57

    Here's the relevant section of the Java EE 6 tutorial:

    Abstract Entities

    An abstract class may be declared an entity by decorating the class with @Entity. Abstract entities are like concrete entities but cannot be instantiated.

    Abstract entities can be queried just like concrete entities. If an abstract entity is the target of a query, the query operates on all the concrete subclasses of the abstract entity:

    @Entity
    public abstract class Employee {
        @Id
        protected Integer employeeId;
        ...
    }
    @Entity
    public class FullTimeEmployee extends Employee {
        protected Integer salary;
        ...
    }
    @Entity
    public class PartTimeEmployee extends Employee {
        protected Float hourlyWage;
    }
    

    If I read this right, your query:

    select s from Sample where s.type = :type
    

    Should only return elements of the specified subtype if type is the discriminator column, so the only thing that's left for you to do is to cast the result list to your requested sub type.

    0 讨论(0)
  • 2020-12-10 13:58

    In JPA 2.0 you can use TYPE expression (though currently it doesn't work with parameters in Hibernate, see HHH-5282):

    select s from Sample s where TYPE(s) = :type
    

    The similar Hibernate-specific expression is .class:

    select s from Sample s where s.class = :type
    
    0 讨论(0)
  • 2020-12-10 14:06

    Do this in your repository

    @Query("SELECT p FROM BaseUserEntity p where p.class=:discriminatorValue")
        public List<BaseUserEntity> findByDiscriminatorValue(@Param("discriminatorValue") String discriminatorValue);
    

    Where BaseUserEntity is your parent entity

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