带有jpa的子查询的内连接

时间:2014-05-30 12:44:36

标签: mysql sql jpa

我想将sql查询转换为jpa查询。

我的两张桌子

看门狗

+---+---------------------+------+
|id |datetime             | stid |
+---+---------------------+------+
|1  | 2011-12-12 09:27:24 |1     |
|2  | 2011-12-13 09:27:31 |2     |
|3  | 2011-12-14 09:27:34 |4     |
|4  | 2011-12-14 09:28:21 |2     |
+-----------------------+------+

station
+----+------+
| id | name |
+----+------+
|  1 | x    |
|  2 | xx   |
|  4 | yy   |
|  7 | z    |
+----+------+

我的班级

public class watchdog{
    @OneToOne
    @JoinColumn(name = "stid")
    private Station station;
    ...
}

我做了一个SQL查询

SELECT wc.stid, st.name
FROM watchdog wc
inner join station st on wc.stid = st.id
inner join (
   select wc2.stid, max(wc2.datetime) as max_date_time from  watchdog wc2 group by     wc2.stid
) ms on wc. stid = ms.stid and wc.datetime = ms.max_date_time

我没有找到任何信息,知道是否可以在jpa中进行。

使用Priyesh解决方案

entityManager.createQuery(sb.toString())=>目标VM发生异常:org.hibernate.hql.ast.QuerySyntaxException: 加入的路径!

SELECT wc
FROM com.xxx.entity.Watchdog wc
join fetch Station st
where wc.datetime = (
  select max(wc2.datetime) from  com.xxx.entity.Watchdog wc2 where wc.stid = wc2.stid   group by wc2.stid
);

SELECT wc
FROM watchdog wc
join fetch station st
where wc.datetime = (
   select max(wc2.datetime) from  watchdog wc2 where wc.station.Id = wc2.station.Id group by wc2.station.Id

);

我没有错误,但我看到mysql进程需要100%的cpu时间

1 个答案:

答案 0 :(得分:1)

您可以尝试将条件放在where而不是内连接中,如下所示:

SELECT wc
FROM watchdog wc
join fetch station st
where wc.datetime = (
   select max(wc2.datetime) from  watchdog wc2 where wc.stid = wc2.stid group by wc2.stid
);