![](/img/trans.png)
[英]Spring Data JPA/Hibernate - using EntityManager for queries
[英]How to nest queries using Spring Data JPA?
如何將以下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子句編寫Criteria的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.