简体   繁体   中英

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

如何用JPA表示exists子句?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM