Search code examples
javahibernatejpql

JPA/Hibernate query construction


I am fetching records from my "record" table. "record" table has many columns tow of which are

  1. client_id, foreign key mapping to client table.
  2. creation_date , date of record creation

I would like to do a query on this table , but I would like to fetch only one record per client(latest creation_date record has preference).

Will following work?

select r.id,r.xx,r.yy
group by(r.client_id),r.creation_date 
from record r 
order by creation_date desc

I tried above and seems records fetched are not of latest creation dates. Hope my question is clear


Solution

  • This should give you a good starting point in HQL.

    from Record as r inner join fetch r.client
    where r.creation_date > (
        select max(rec.creation_date) from Record rec
        where rec.client.client_id = r.client.client_id
    )
    

    This of course assumes that your Record has a reference to its parent Client called client.