mardi 9 juin 2015

JPA 2.0 CriteriaQuery with predicate on type being a class or any subclass of

Assuming the following entity classes and hierarchy:

@Entity
Class Ticket {

    @ManyToOne(optional = true)
    private Customer customer;    

}

@Entity
Class Customer {}

@Entity
Class Person extends Customer {}

@Class CustomPerson extends Person {}

How can I query for all tickets which have customer of type Person or any subclass of Person (i.e. CustomPerson)?

I can easily create a predicate on type:

Predicate p = criteriaBuilder.equal(Ticket_...type(), criteriaBuilder.literal(Person.class));

but this will filter out CustomPerson.

Unless there is a generic way to handle this (in JPA 2.0), I could overcome the issue if I could determine at runtime all entities extending Person; in this scenario I could use

Predicate p = criteriaBuilder.in(Ticket_...type(), listOfPersonSubclasses);

Aucun commentaire:

Enregistrer un commentaire