S.P.
S.P.

Reputation: 2564

How to get only one value of a String that have set some values in grails and is not a list?

I have one column in my database that have this values "Bob;Steve;Fred". This column is a String (not a list) and I want to be able to build a query that give me the value that I'm pass throught the params.

This is my domain:

String name (values that contain name is: Bob;Steve;Fred)

That I'm trying to do is build a query that only get me the name that I pass in the method:

This is the My method and that I'm trying to do:

def updateName(String myName) {
    MyDomain md = MyDomain.findByName(myName)
    if (!md) {
       log.warn "name not found [" + name+ "]"
    }

}

With this, I'm getting always md = null;

That I want is, for example. If I pass myName=Bob that I want is find Bob in my string name that have three names (Bob;Steve;Fred):

 MyDomain md = MyDomain.findByName(Bob)
 md should be = Bob

Thanks in advance

Upvotes: 0

Views: 649

Answers (3)

Simpson
Simpson

Reputation: 593

You can try doing this too:

MyDomain md = MyDomain.findByName("%" + myName + "%")

Check the doc: https://grails.github.io/grails-doc/2.4.4/ref/Domain%20Classes/findBy.html

Upvotes: 0

Mike B
Mike B

Reputation: 2776

INTRO
Although there is one answer for existing problem, as @tim_yates pointed out, there are possible problems with using my answer as well as Your approach of setting the domain class is not the best

How to set list in domain
Grails domain classes has hasMany selector, so your domain class should look like this:

class MyDomain {
    static hasMany = [names: String]
    List names
}

How to add a name
When having a domain object and wanting to add another name to the list, you can use myDomainObject.addToNames(thename)

How to retrieve by name
As I stated before, this requires createCriteria() :

def results = MyDomain.createCriteria().list{
    "in"("names",someName)
}

This will return a list of all domain objects. If you want to get some data from them, you can loop through using each and refer to one item using it:

results.each{
    println it.names
}

Upvotes: 0

Mike B
Mike B

Reputation: 2776

These default functions like findBySomething() work only with exact values. Because they are translated to Hibernate queries and in the query it checks is the value of object is equal to the passed value.
But Grails has a thing called criteria and if I understand correctly (that you want domain value that INCLUDES your passed String), you should go like this:

def results = MyDomain.createCriteria().list{
    ilike("name", "%"+myName+"%")
}


ALSO
I don't get what you are trying to achieve, but this structure doesn't seem good (to store possible values in a string like that)

Upvotes: 1

Related Questions