我正在尝试使用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;
...
}
SpecialItem
@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
的所有SpecialItem
,其中SpecialItem.specialAttr
具有某些价值?
答案 0 :(得分:13)
如果使用JPA 2.1,您可以使用
"SELECT b FROM Box b WHERE TREAT(b.item as SpecialItem).specialAttr = :specialAttr"
或
CriteriaQuery<Box> q = cb.createQuery(Box.class);
Root<Box> box= q.from(Box.class);
Join<Box, Item > order = box.join("item");
q.where(cb.equal(cb.treat(order, SpecialItem.class).get("specialAttr"),
qb.parameter(String.class, "specialAttr")));
q.select(Box);
答案 1 :(得分:5)
我只想通过生成的元模型扩展Chris对Criteria API的答案。
CriteriaQuery<Box> q = cb.createQuery(Box.class);
Root<Box> box= q.from(Box.class);
Join<Box, Item> order = box.join(Box_.item);
q.where(cb.equal(cb.treat(order, SpecialItem.class).get(SpecialItem_.specialAttr), "searchValue");
q.select(Box);