2012-03-26 2 views
5

슈퍼 클래스에없는 서브 클래스 속성을 검색하고 슈퍼 클래스의 모든 객체를 반환하는 쿼리를 작성하려고합니다. 현재 person.get ("specialAttribute")을 시도 할 때 NullPointerException이 발생합니다.JPA CriteriaQuery로 하위 클래스 속성을 검색하는 방법은 무엇입니까?

@Inheritance(strategy = InheritanceType.JOINED) 
@Entity 
public abstract class Person { 
    public String searchableAttribute; 
} 

@Entity 
@Table(name = "normal_person") 
public class NormalPerson extends Person { 

} 

@Entity 
@Table(name = "special_person") 
public class SpecialPerson extends Person { 
    @Column(nullable = false, unique = true) 
    public String specialAttribute; 
} 

// Controller method 

    Root<Person> person = query.from(Person.class); 
    query.where(
      builder.or(
        builder.like(person.<String>get("specialAttribute"), "foo"), 
        builder.like(person.<String>get("searchableAttribute"), "foo") 
      ) 
    ); 

답변

9

힌트 다음에 나와있는 문제가 here으로 해결되었습니다.

Root<Person> person = query.from(Person.class); 

Subquery<SpecialPerson> subQuery = query.subquery(SpecialPerson.class); 
Root<SpecialPerson> specialPersonRoot = subQuery.from(SpecialPerson.class); 

subQuery.select(specialPersonRoot); 
subQuery.where(builder.like(specialPersonRoot.<String>get("specialAttribute"), "foo")); 

query.where(
     builder.or(
       builder.in(person).value(subQuery) 
       builder.like(person.<String>get("searchableAttribute"), "foo") 
     ) 
); 
관련 문제