criteria in grails

In the Grails framework, criteria is a way to construct database queries using a fluent API. It allows you to build complex queries by chaining together different criteria methods. These methods provide various options for filtering and ordering query results.

To use criteria in Grails, you typically start by creating a new instance of the DetachedCriteria class. This class represents a query that is not yet associated with a specific domain class. Once you have a DetachedCriteria instance, you can use its methods to define the criteria for your query.

Some commonly used criteria methods in Grails include:

  • eq(property, value): Specifies that the given property should be equal to the specified value.
  • ne(property, value): Specifies that the given property should not be equal to the specified value.
  • gt(property, value): Specifies that the given property should be greater than the specified value.
  • lt(property, value): Specifies that the given property should be less than the specified value.
  • isNull(property): Specifies that the given property should be null.
  • isNotNull(property): Specifies that the given property should not be null.
  • like(property, value): Specifies that the given property should match the specified value using a SQL-like pattern.
  • inList(property, values): Specifies that the given property should be in the list of specified values.

Once you have defined your criteria, you can execute the query using the list() method to retrieve the results. For example:

def criteria = MyDomainClass.createCriteria()
def results = criteria {
    eq("status", "active")
    gt("age", 18)
    order("name", "asc")
    maxResults(10)
}

In this example, we create a criteria query for the MyDomainClass domain class. We specify that the "status" property should be equal to "active", the "age" property should be greater than 18, and the results should be ordered by the "name" property in ascending order. We also limit the number of results to 10.

This is a basic overview of using criteria in Grails. There are many more methods and options available for constructing queries using criteria. You can refer to the Grails documentation for more information on using criteria in your Grails applications.