I'm trying to achieve something like the following, using the JPA Criteria API:
SELECT b FROM Box b JOIN SpecialItem s WHERE s.specialAttr = :specialAttr
The objects are
Box
@Entity
public class Box implements Serializable {
...
@ManyToOne
@JoinColumn( name = "item_id" )
Item item;
...
}
Item
@Entity
@Inheritance( strategy = InheritanceType.JOINED )
public class Item implements Serializable {
@Id
private String id;
...
}
SpecialItem
@Entity
public class SpecialItem extends Item {
private String specialAttr;
...
}
My attempt
EntityManager em = getEntityManager();
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery( Box.class );
Root from = cq.from( Box.class );
// Nothing to specify SpecialItem over Item!
Join join = from.join("item", JoinType.LEFT);
// java.lang.IllegalArgumentException: Unable to
// resolve attribute [specialAttr] against path [null]
Path p = join.get( "specialAttr" );
Predicate predicate = cb.equal( p, "specialValue" );
cq.where( predicate );
Not surprisingly it throws an exception because specialAttr isn't a member of class Item.
How can I return all the Box
es that contain a SpecialItem
, where the SpecialItem.specialAttr
has some value?
Box
es that contain aSpecialItem
TOO? I'd be glad to hear from you. – Greening