Search code examples
grailscriteriahibernate-criteria

How to bulid a criteria query to get the data of my domain


I know that have to be really easy, but I'm new in grails and I don't find any clear answer. That I want to do is read and get with a criteria query the data that I have in my domain do a search for each parameter.

This is my domain Person:

    String name
    String surname
    String address
    String village
    String country

This is that I'm trying to do:

def getData = Person.createCriteria()

I can see in the log that I have an object (com.mypackagename.Person: 1.), but not the data that I have in the database. example (myname, mysurname, myaddress, myvillage, mycountry)

I only have one row of data in my database and I want to get the data of every column and do a search for each parameter

Thanks in advance.


Solution

  • Let me show you the code first, then I'll explain it:

    class SomeController {
    
        def search() {
            def people = Person.withCriteria {
                params
                    .findAll { name, value -> name in ['name', 'surname', 'address', 'village', 'country'] }
                    .each { name, value -> eq(name, value) }
            }
    
            // Do as you please with 'people'; a list of Person instances.
        }
    }
    

    Ok, so let's say you have a controller method (ex. search()) which receives the query parameters from the user. The parameters would be in the params Map. For example, if the user searches for the name John and the country USA, params would look like this: [name: 'John', country: 'USA']. Even though there are other search parameters available, we won't use them because the user did not specify them.

    Within the criteria query, first search for the param key/value pairs which you care about; the searchable properties of Person. Then, for each of those pairs call eq(String propertyName, Object value) to set up the query criteria (the WHERE clause).

    Using the example data, Hibernate will generate SQL that looks something like this:

    SELECT name, surname, address, village, country 
    FROM person 
    WHERE name = 'john' AND country = 'USA'
    

    And that's it!

    Note: You will see the same output in the log (ex. com.mypackagename.Person: 1). That's because you're logging personInstance.toString(). So if you want the log entry to look differently, you'll need to override Person.toString() A very easy way to remedy this is to use Groovy's @ToString AST.

    For more about creating criteria queries, take a look at my series of articles. I cover criteria queries using SQL terminology.