gpt4 book ai didi

java - 如何使用 Spring Data JPA 嵌套查询?

转载 作者:行者123 更新时间:2023-11-30 07:57:13 24 4
gpt4 key购买 nike

如何将以下 SQL 转换为 Criteria?

SELECT DISTINCT <column name> FROM <table>
WHERE <some other column> IN
(SELECT DISTINCT <column name 2> FROM <table 2>
WHERE <some other column 2> IN
(SELECT <column name 3> FROM <table 3>
WHERE <some other column 3> IN
(SELECT <column name 4> from <table 4>
WHERE <some other column 4> IN (0,1,2,3,4))))

以下是我将搜索的列值类型:

Column           Value Type
<column name> String
<column name 2> String
<column name 3> Long
<column name 4> Long

最佳答案

要翻译的 SQL:

SELECT DISTNCT <column name> FROM <table>
WHERE <some other column> IN
(SELECT DISTINT <column name 2> FROM <table 2>
WHERE <some other column 2> IN
(SELECT <column name 3> FROM <table 3>
WHERE <some other column 3> IN
(SELECT <column name 4> from <table 4>
WHERE <some other column 4> IN (0,1,2,3,4))))

Column Value Type
<column name> String
<column name 2> String
<column name 3> Long
<column name 4> Long

SQL 转换为 JPA 标准:

CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<String> cqTable = cb.createQuery(String.class);
Root<table> fromTable = cqTable .from(<table>.class);

Subquery<String> cqTable2 = cqTable.subquery(String.class);
Root<table 2> fromTable2 = cqTable2.from(<table 2>.class);

Subquery<Long> cqTable3 = cqTable2.subquery(Long.class);
Root<table 3> fromTable3 = cqTable3.from(<table 3>.class);

Subquery<Long> cqTable4 = cqTable3.subquery(Long.class);
Root<table 4> fromTable4 = cqTable4.from(<table 4>.class);

cqTable4 = cqTable4.select(fromTable4.get("column 4").as(Long.class))
.where(fromTable4.get("some other column 4").in(new ArrayList<String>(){{
add("0");
add("1");
add("2");
add("3");
add("4");}}));

cqTable3 = cqTable3.select(fromTable3.get("column name 3").as(Long.class))
.where(fromTable3.get("some other column 3")
.in(cqTable4));

cqTable2 = cqTable2.select(fromTable2.get("column name 2").as(String.class))
.distinct(true).where(fromTable2.get("some other column 2")
.in(cqTable3));

cqTable = cqTable.select(fromTable.get("column name").as(String.class))
.distinct(true).where(fromTable.get("some other column").in(cqTable2)));

List<String results = emf.createEntityManager().createQuery(cqTable ).getResultList();

我希望这能够帮助那些正在努力编写带有嵌套 SELECT 和 IN 子句的条件的人。

关于java - 如何使用 Spring Data JPA 嵌套查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32504853/

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