如何用JPA表示exists
子句?
最佳答案
首先(我们在Oracle上并且有一个DUAL表):
@Entity()
@Table(name = "DUAL")
@ReadOnly
public class Dual {
@Id
String dummy;
public String getDummy() {
return dummy;
}
}
然后:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Dual> cq = cb.createQuery(Dual.class);
Subquery<ProtokollSatz> sq = cq.subquery(ProtokollSatz.class);
Root<ProtokollSatz> root1 = sq.from(ProtokollSatz.class);
sq.where(
cb.and(
cb.equal(root1.<Integer> get("field1"), Integer.valueOf(field1)),
cb.equal(root1.<Integer> get("field2"), Integer.valueOf(field2))));
cq.where(cb.exists(sq));
TypedQuery<Dual> query = em.createQuery(cq);
boolean ifExists = query.getResultList().size() > 0;
你得到:
SELECT t0.DUMMY FROM DUAL t0 WHERE EXISTS
(SELECT ? FROM PROTOKOLL_SAETZE t1 WHERE ((t1.FIELD1 = ?) AND (t1.FIELD2 = ?)))
经过eclipselink测试。