开发者

How to verify whether a record with certain field values exists in a DB with JPA?

How to express the exists clause with J开发者_开发知识库PA?


First (we are on Oracle and have a DUAL Table):

@Entity()
@Table(name = "DUAL")
@ReadOnly
public class Dual {
    @Id
    String dummy;

    public String getDummy() {
        return dummy;
    }
}

Then:

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;

You get:

SELECT t0.DUMMY FROM DUAL t0 WHERE EXISTS
 (SELECT ? FROM PROTOKOLL_SAETZE t1 WHERE ((t1.FIELD1 = ?) AND (t1.FIELD2 = ?)))

Tested with eclipselink.


Exists is perfectly legal in JPQL, just use it. Perhaps I don't understand the question though? It's a bit terse :)

SELECT user 
FROM SOUsers user
WHERE EXISTS (SELECT user0 
              FROM SOUsers user0 
              WHERE user0 = user.bestFriendWhoAnswersTheirQuestions
                    and user0.name = 'Roman')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜