简体   繁体   中英

Inner join with subquery with jpa

I would like to convert a sql query to a jpa query.

My two tables

watchdog

+---+---------------------+------+
|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    |
+----+------+

My class

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

I have done a sql query

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

I don't found any information to know if it's possible to do it in jpa.

with Priyesh solution i get

entityManager.createQuery(sb.toString()) = >Exception occurred in target VM: org.hibernate.hql.ast.QuerySyntaxException: Path expected for join!

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
);

with

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

);

i have no error but i see the mysql process take 100% cpu time

You can try by putting the condition in the where instead of the inner join like below:

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
);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM