本文介绍了如何在CriteriaQuery中查询超类的地方引用特定于子类的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用JPA Criteria API实现以下目标:
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
对象是
框
@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类的成员.
Not surprisingly it throws an exception because specialAttr isn't a member of class Item.
如何返回所有包含SpecialItem
的Box
,其中SpecialItem.specialAttr
具有某些值?
How can I return all the Box
es that contain a SpecialItem
, where the SpecialItem.specialAttr
has some value?
推荐答案
如果使用JPA 2.1,则可以使用
If using JPA 2.1 you might use
"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);
这篇关于如何在CriteriaQuery中查询超类的地方引用特定于子类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!