2013-03-12 69 views
4

財產,我有兩個實體:JPA 2條件查詢的超

@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

我的查詢:

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 [[email protected]: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.; 

如何建立這種情況下的typesaft條件查詢?

回答

3

我建議generate規範metamodel(鏈接是Hibernate文檔,但概念,如果是JPA)。然後Kind_.familienname可以直接用於查詢,因爲Kind_Person_繼承familienname

如果這不是一個選項,然後從超屬性應通過超類的元模型被引用:

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

丹克你了。它解決了。 – 2013-03-13 09:13:43