0

I need to write a criteria or HQL that selects InterfaceVersion only with the latest version for each interfaceCode. Version consists of majorVersion.minorVersion.editVersion.

exemple:

InterfaceVersion table:

id | interface_code_id | major_version | minor_version | edit_version
---|-------------------|---------------|---------------|-------------
 1 |                 1 |             1 |             1 |            6
 2 |                 1 |             1 |             5 |            0
 3 |                 2 |             1 |             0 |            0
 4 |                 2 |             0 |             1 |            0
 5 |                 2 |             2 |             0 |            1
 6 |                 2 |             1 |             3 |            6

expected result would be:

InterfaceVersions instances with ids [2, 5]

I have this GORM domain classes(simplified):

InterfaceCode{
    int id
    String code

    static hasMany = [ versionList: InterfaceVersion]
}

InterfaceVersion{
    int id
    InterfaceCode interfaceCode
    int majorVersion
    int minorVersion
    int editVersion

    static belongsTo = [ InterfaceCode ]

    static constraints = {
        interfaceCode(unique:['majorVersion','minorVersion','editVersion'])
    }
}

So far I've been able to come up with this sql:

SELECT t1.*
FROM Interface_Version  t1
  Left Outer Join Interface_Version  T2
    On (T1.Interface_Code_Id = T2.Interface_Code_Id And 
      (T1.Major_Version < T2.Major_Version Or 
      (T1.Major_Version = T2.Major_Version And T1.Minor_Version < T2.Minor_Version) Or 
      (T1.Major_Version = T2.Major_Version And T1.Minor_Version = T2.Minor_Version And T1.Edit_Version < T2.Edit_Version ) )
      )
WHERE t2.id IS NULL

Can you please convert this sql to hql or critearia or come up with something nicer ?

4

0 回答 0