Search code examples
hibernategrailsgrails-ormhibernate-5.x

Grails 3 - use Criteria to find string in list of strings


I have the following domain class and want to find all groups that start with the group name (if a group name is entered) and contain one of the the groupStrings (if a group string is entered):

class Group {
    String name
    List groupStrings
    static hasMany = [
        groupStrings : String
    ]
}

I tried:

String groupNameToFind = ...
String groupStringToFind = ...

List<Long> groupIds = Group.createCriteria().listDistinct() {
    projections {
        property 'id'
    }
    if(groupNameToFind) {
        ilike('name', groupNameToFind + '%')
    }
    if(groupStringToFind) {
        eq('groupStrings', groupStringToFind)
    }
}

I also tried:

List<Long> groupIds = Group.createCriteria().listDistinct() {
    projections {
        property 'id'
    }
    if(groupStringToFind) {
        createAlias('groupStrings', 'gs', JoinType.LEFT_OUTER_JOIN)
        eq('gs', groupStringToFind)
    }
    if(groupNameToFind) {
        ilike('name', groupNameToFind + '%')
    }
}

Both of these produce an error when trying to find a group string. What is the correct syntax?


Solution

  • Your domains are a bit wierd. I would make two domains not just one. You need a Group Domain and a GroupString Domain. The Group can have a hasMany GroupString, and the GroupString can just be a string, and maybe belongs to. I think that would be the only way to do it via query. Otherwise you can get all the Groups and do a .find {closure}