我用MySQL编写了这个查询,它可以工作:
select c.*
from macchine.check_list c
join (select pratica, documentazione, max(versione) as versione
from macchine.check_list
group by pratica, documentazione) c2
on c.pratica = c2.pratica
and c.documentazione = c2.documentazione
and c.versione = c2.versione;
然后我尝试使用JPA存储库在我的网络应用上移动此查询:
@Query("select t1 from CheckList as t1 join "
+ "(select pratica, documentazione, max(versione) as versione from CheckList group by pratica, documentazione) as t2 "
+ "on t1.pratica = t2.pratica and "
+ "t1.documentazione = t2.documentazione and "
+ "t1.versione = t2.versione")
但是它不起作用,因为我知道,要创建一个与JPA存储库的连接,你必须做一些像:
form table1 t1 join t1.table2 t2 on etc.
但是在这种情况下我需要在同一个表上进行连接,那么我该怎么做呢?
答案 0 :(得分:1)
我解决了添加nativeQuery = true
。
所以这是我的问题:
@Query(value = "select t1.* from macchine.check_list as t1 join "
+ "(select pratica, documentazione, max(versione) as versione from macchine.check_list group by pratica, documentazione) as t2 "
+ "on t1.pratica = t2.pratica and "
+ "t1.documentazione = t2.documentazione and "
+ "t1.versione = t2.versione where t1.pratica = :pratica", nativeQuery = true)
要明确这是我的表:
+----+----------------+---------+----------+---------+
| id | documentazione | pratica | versione | ....... |
+----+----------------+---------+----------+---------+
| 1 | 1 | 1 | 1 | |
+----+----------------+---------+----------+---------+
| 2 | 2 | 1 | 1 | |
+----+----------------+---------+----------+---------+
| 3 | 3 | 1 | 1 | |
+----+----------------+---------+----------+---------+
| 4 | 1 | 1 | 2 | |
+----+----------------+---------+----------+---------+
并使用此查询结果如下:
+----+----------------+---------+----------+---------+
| id | documentazione | pratica | versione | ....... |
+----+----------------+---------+----------+---------+
| 4 | 1 | 1 | 2 | |
+----+----------------+---------+----------+---------+
| 2 | 2 | 1 | 1 | |
+----+----------------+---------+----------+---------+
| 3 | 3 | 1 | 1 | |
+----+----------------+---------+----------+---------+
答案 1 :(得分:0)
JPA不支持JOIN
内联视图。通过这种连接过滤结果的主要替代方法(在JPQL和SQL中)通过WHERE
子句中的相关子查询过滤它们:
select t1
from CheckList t1
where t1.versione = (
select max(versione)
from CheckList t2
where t2.pratica = t1.pratica
and t2.documentazione = t1.documentazione
)
答案 2 :(得分:0)
您可以在MySQL中使用子选择创建视图,然后将该视图映射到Java实体并在CheckList
中添加必要的映射:
@OneToOne
@JoinColumns(
{
@JoinColumn(name="pratica"),
@JoinColumn(name="documentazione"),
@JoinColumn(name="versione")
}
private MaxCheckList maxCheckList;
@Query("select t1 from CheckList as t1 join maxCheckList t2")