JPA GROUP BY entity - is this possible?

前端 未结 3 1601
逝去的感伤
逝去的感伤 2021-02-07 03:16

Is possible to select data in JPA with grouping by referenced entity?

I mean: I have two entities - insurance and referenced many-to-one vehicle. Insurance entity has va

相关标签:
3条回答
  • 2021-02-07 03:46

    Apparently the JPA spec allows that but at least Hibernate's implementation does not support it (see HHH-2436 and HHH-1615).

    0 讨论(0)
  • 2021-02-07 03:57

    If you pass an entity inside the GROUP BY, Hibernate automatically adds its id to the transformed SQL of the underlying DB. In addition, the values in the GROUP BY must exist in the SELECT clause. Thus, instead of select the whole object, you can select its id, then from those ids, you can retrieve the object again.

     SELECT DISTINCT v.vehicle.id, max(v.validTill)
     FROM TraInsurance v 
     GROUP BY v.vehicle.id
     ORDER BY max(v.validTill)
    

    If it takes time and requires DB hits to retrieve Vehicle objects from their ids, you can select all of Vehicle's attributes in the SELECT and put them in the GROUP BY. Then you can construct the Vehicle object from those attributes without accessing to DB.

    0 讨论(0)
  • 2021-02-07 03:58

    Please explicitly use JOIN in this use case:

    SELECT ve, MAX(v.validTill)
    FROM TraInsurance v JOIN v.vehicle ve
    GROUP BY ve
    ORDER BY MAX(v.validTill)
    
    0 讨论(0)
提交回复
热议问题