How would I translate the following SQL into 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))))
Here are the Column value types I'll be searching on:
Column Value Type
<column name> String
<column name 2> String
<column name 3> Long
<column name 4> Long
SQL to translate:
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 Translated into JPA Criteria:
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();
I hope this is able to help someone who is struggling to write Criteria with nest SELECT and IN clauses.
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.