【问题标题】:How to search on subclass attribute with a JPA CriteriaQuery?如何使用 JPA CriteriaQuery 搜索子类属性?
【发布时间】:2012-03-26 16:27:30
【问题描述】:

我正在尝试编写一个查询来搜索不在其超类中的子类属性并返回超类的所有对象。目前,当我尝试做 person.get("specialAttribute") 时,我得到了 NullPointerException。

@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")
            )
    );

【问题讨论】:

    标签: hibernate jpa-2.0 criteria-api


    【解决方案1】:

    根据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")
            )
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-29
      相关资源
      最近更新 更多