Ondrej Kvasnovsky
Ondrej Kvasnovsky

Reputation: 4643

How to make a query with usage of like operator over a string collection in GORM

Assume a domain class called User. User class looks like this:

class User {
     List<String> values
}

The collection values contains strings like "http://example.com/x", "http://google.com/y", "http://google.com/z" and so on...

Let's say we want to build a query which gets all the users that have specific string in the collection values (e.g. "google.com"). Something like this:

def criteria = User.createCriteria()
def results = criteria.listDistinct () {
  and {
    user.values.each {  like('someField', '%${it}%') }
  }
}

Any ideas?

Upvotes: 3

Views: 5287

Answers (3)

Igor Aguiar
Igor Aguiar

Reputation: 176

After a lot of trying and researching, I found this will work with Grails 2.4.0, I don't know about older versions.

Cat.withCriteria {
    createAlias('nicknames', 'n') 
    ilike 'n.elements', '%kitty%'
}

The trick is to use 'n.elements'

Upvotes: 0

Ondrej Kvasnovsky
Ondrej Kvasnovsky

Reputation: 4643

I have found the answer by experimentation. The solution is:

def criteria = User.createCriteria()
def results = criteria.listDistinct () {
  and {
    user.values.each {  like('someField', '%'+it+'%') }
  }
}

Upvotes: 3

mjs
mjs

Reputation: 22347

I am not sure what you are doing with your suggested answer. I have never seen that usage of each in the criteria query before.

This question has been asked many times before but never given an answer. The problem is that you are queriyng a String association, which is not a domain class. If you would make your own String domain class for example ondrej.String { String strValue } then you would be able to do :

User.withCriteria {

 values { ilike("strValue", "...") }

}

The problem is not having access to the value of the String object. The value of the String class is called value, but it is a char array, so I do not believe the following will work:

User.withCriteria {

 values { ilike("value", "...") }

}

You could try using :

User.withCriteria {

 values { ilike("toString", "...") }

}

or something else instead of toString ... I do not have the possibility to test this right now.

Hope that helps

Upvotes: 0

Related Questions