JPA 2 Criteria超类的查询属性

时间:2013-03-12 14:44:42

标签: jpa-2.0 criteria-api

我有两个实体:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Person implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GEN_Person")
    @SequenceGenerator(name = "GEN_Person", sequenceName = "seq_person" , initialValue = 1, allocationSize = 10)
    @Column(nullable = false)
    private Long id;
    private String familienname;
    private String vorname;

    ...
}

子类:

@Entity
@DiscriminatorValue(value = "KIND")
public class Kind extends Person implements Serializable {
     ... // other properties
}

我希望通过jpa 2中的条件查询找到所有Kind-Entities。

我的查询:

public List<Kind> find(String f_name, String v_name) {
    CriteriaBuilder       cb         = em.getCriteriaBuilder();
    CriteriaQuery<Kind> cq         = cb.createQuery(Kind.class);
    EntityType<Kind>    type       = em.getMetamodel().entity(Kind.class);
    Root<Kind>          kindRoot = cq.from(Kind.class);

// Constructing list of parameters
List<Predicate> predicates = new ArrayList<Predicate>();

if ((null != f_name) &&!f_name.isEmpty()) {
    predicates.add(cb.like(cb.lower(kindRoot.get(type.getDeclaredSingularAttribute("familienname",
            String.class))), "%" + f_name.toLowerCase() + "%"));
}

if ((null != v_name) &&!v_name.isEmpty()) {
    predicates.add(cb.like(cb.lower(kindRoot.get(type.getDeclaredSingularAttribute("vorname",
            String.class))), "%" + v_name.toLowerCase() + "%"));
}

cq.select(kindRoot).where(predicates.toArray(new Predicate[] {}));

    return (List<Kind>) em.createQuery(cq).getResultList();
}

但我收到了错误:

     javax.ejb.EJBException: EJB Exception: ; nested exception is: 
        java.lang.IllegalArgumentException: The declared attribute [familienname] from the managed type [EntityTypeImpl@441955560:Kind [ javaType: class com.itech_progress.kiwi.entities.Kind descriptor: 
RelationalDescriptor(com.itech_progress.kiwi.entities.Kind --> [DatabaseTable(PERSON), DatabaseTable(KIND)]), mappings: 19]] is not present - however, it is declared on a superclass.;

如何为此案例构建typeaft条件查询?

1 个答案:

答案 0 :(得分:3)

我建议generate规范metamodel(链接是Hibernate文档,但是对于JPA是概念)。然后Kind_.familienname可以直接用于查询,因为Kind_会从familienname继承Person_

如果那不是一个选项,那么超类的属性应该通过超类的元模型引用:

EntityType<Person> metamodelPerson = em.getMetamodel().entity(Person.class);
...
metamodelPerson.getDeclaredSingularAttribute("familienname", String.class)