gpt4 book ai didi

jpa - 在 jpa 条件 api 中使用 NOT EXISTS 构建查询

转载 作者:行者123 更新时间:2023-12-04 01:44:52 27 4
gpt4 key购买 nike

我有两个名为 table1 的表,table2。两个表都有相同的字段数。这两个表之间没有关系。我的要求是我想要 table1 中的所有记录,而 table2 中没有。所以我使用 Criteria API 编写了一个查询。但它没有给出正确的结果。由于我是这个 JPA 和标准 API 的新手,任何人都可以指出我做错的地方。我使用下面的代码来做到这一点。

CriteriaBuilder cb = mediationEntityManager.getCriteriaBuilder();
CriteriaQuery<Table1> cq = cb.createQuery(Table1.class);
Root<Table1> table1 = cq.from(Table1.class);
cq.select(table1)

Subquery<Table2> subquery = cq.subquery(Table2.class)
Root table2 = subquery.from(Table2.class)
subquery.select(table2)
cq.where(cb.not(cb.exists(subquery)))
TypedQuery<Table1> typedQuery = mediationEntityManager.createQuery(cq);
List<Table1> resultList = typedQuery.getResultList();

MySQL 查询:

SELECT table1 
FROM table1 table1
WHERE NOT EXISTS (SELECT table2
FROM table2 table2
WHERE table2.name = table1.name
AND table2.education = table1.education
AND table2.age = table1.age)
AND table1.name = 'san'
AND table1.age = '10';

我需要上述 MySQL 查询的 JPA 标准 API 查询。

最佳答案

您可以使用 Criteria API 尝试以下代码。我没试过,但你可以尝试相应地修改代码。

CriteriaBuilder cb = mediationEntityManager.getCriteriaBuilder();  
CriteriaQuery<Table1> query = cb.createQuery(Table1.class);
Root<Table1> table1 = query.from(Table1.class);
query.select(table1);
//--
Subquery<Table2> subquery = query.subquery(Table2.class);
Root<Table2> table2 = subquery.from(Table2.class);
subquery.select(table2);
//--
List<Predicate> subQueryPredicates = new ArrayList<Predicate>();
subQueryPredicates.add(cb.equal(table1.get(Table1_.name), table2.get(Table2_.name)));
subQueryPredicates.add(cb.equal(table1.get(Table1_.age), table2.get(Table2_.age)));
subQueryPredicates.add(cb.equal(table1.get(Table1_.education), table2.get(Table2_.education)));
subquery.where(subQueryPredicates.toArray(new Predicate[]{}));
//--
List<Predicate> mainQueryPredicates = new ArrayList<Predicate>();
mainQueryPredicates.add(cb.equal(table1.get(Table1_.name), "san");
mainQueryPredicates.add(cb.equal(table1.get(Table1_.age), "10");
mainQueryPredicates.add(cb.not(cb.exists(subquery)));
//--
query.where(mainQueryPredicates.toArray(new Predicate[]{}));
TypedQuery<Table1> typedQuery = mediationEntityManager.createQuery(query);
List<Table1> resultList = typedQuery.getResultList();

此外,您可以尝试以下 JPQL 查询,它更易于理解、更改和调试。

SELECT t1 
FROM table1 t1,
table2 t2
WHERE t1.name = 'san'
AND t1.age = '10'
AND (t2.name <> t1.name
AND t2.education <> t1.education
AND t2.age <> t1.age);

关于jpa - 在 jpa 条件 api 中使用 NOT EXISTS 构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13859780/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com