JPA2 Criteria queries on entity hierarchy

suppose i have the following entity domain:

@Entity
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE")
public abstract class Entity1 {
//some attributes
}

@Entity 
@DiscriminatorValue("T1")
public class Entity2 extends Entity1 {
    @OneToMany(fetch=FetchType.EAGER, cascade = { CascadeType.ALL }, mappedBy="parent")
    @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
    private Set<Entity1Detail> details = new HashSet<Entity1Detail>();
}

@Entity
public class Entity1Detail {
    @ManyToOne
    @JoinColumn(name="REF")
    private Entity2 parent;

    @Basic
    private Integer quantity;
}

@Entity
@DiscriminatorValue("T2")
public class Entity3 extends Entity1 {
//some other attributes
}

when i do a JPQL query:

select e from Entity1 e left join e.details d where d.quantity > 1

it runs well (left join ;P). however when i try to construct the same query using JPA2 Criteria API:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery q = builder.createQuery();
Root r = q.from(Entity1.class);
q.select(r);
q.where(builder.gt(r.join("details", JoinType.LEFT).get("quantity"), 1));

i get NPE in "join" because the attribute "details" doesn't belong to Entity1 (which is actually true, i have to select on Entity2.class instead). the thing is that when i have to construct my dynamic query using Criteria API i don't really know anything about hierarchy, i'm just passed a Class.

i understand that Criteria API is typesafe and all that, but is there a way to work around this? with aliases maybe (as before i used Hibernate Criteria API, traversing joins with aliases):

Criteria c = session.createCriteria(Entity1.class);
c.createAlias("details", "d");
c.add(Restrictions.ge("d.quantity", 1));
5
задан Yog Sothoth 28 September 2010 в 14:49
поделиться