我正在尝试使用 JPA Criteria API 实现以下目标:
SELECT b FROM Box b JOIN SpecialItem s WHERE s.specialAttr = :specialAttr
对象是
盒子
@Entity
public class Box implements Serializable {
...
@ManyToOne
@JoinColumn( name = "item_id" )
Item item;
...
}
物品
@Entity
@Inheritance( strategy = InheritanceType.JOINED )
public class Item implements Serializable {
@Id
private String id;
...
}
特殊物品
@Entity
public class SpecialItem extends Item {
private String specialAttr;
...
}
我的尝试
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 );
毫不奇怪,它会引发异常,因为 specialAttr 不是 Item 类的成员。
我怎样才能返回所有Box
包含 a 的 es SpecialItem
,其中esSpecialItem.specialAttr
有一些价值?