Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA 2 Criteria query property of superclass

I have two Entities:

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

    ...
}

And the subclass:

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

I want find all Kind-Entities through a criteria query in jpa 2.

My Query:

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();
}

But I get so error:

     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.;

How can i build a typesaft criteria query for this case?

like image 491
H. Zhang Avatar asked Oct 21 '22 15:10

H. Zhang


1 Answers

I would suggest to generate canonical metamodel (link is to Hibernate documentation, but concept if for JPA). Then Kind_.familienname can directly be used in query, because Kind_ inherits familienname from Person_.

If that is not an option, then attributes from the superclass should be referenced via metamodel of superclass:

EntityType<Person> metamodelPerson = em.getMetamodel().entity(Person.class);
...
metamodelPerson.getDeclaredSingularAttribute("familienname", String.class)
like image 132
Mikko Maunu Avatar answered Oct 25 '22 19:10

Mikko Maunu