DomainClass Dynamic Methods

Domain Class Dynamic Methods & Properties

Properties

errors

Description

A list of errors from the last call to the "validate" or "save" method. The property is an implementation of org.springframework.validation.Errors.

Example
def b = new Book(title:"The Shining")
if(!b.validate()) {
    b.errors.each {
          println it
    }
}

You can create your own errors in your controllers using the reject() and rejectValue() methods:

if (params.password != params.confirm_password) {

    user.errors.reject('user.password.doesnotmatch',                                    // Error code, see grails-app/i18n/message.properties
                       ['password', 'class User'].toArray(),                            // Groovy ListArray cast to Object[]
                       '[Property [{0}] of class [{1}] does not match confirmation]')   // Default mapping string

    // The following helps with field highlighting in your view
    user.errors.rejectValue('password',                                                 // Field in view to highlight using <g:hasErrors> tag
                            'user.password.doesnotmatch')                               // i18n error code

    render(view:'signup', model:[user:user])
    return;
}



constraints

Description

A list of org.codehaus.groovy.grails.validation.ConstrainedProperty instances applied against the domain class by the constraints property (see Validation)

Example
def b = new Book(title:"The Shining")
b.constraints.each {
      println it.name
      println it.maxLength
}



properties

Description

Allows access to the domain class properties as a map and perform types conversion when set allowing properties to be set from request parameters for example.

Example
def b = new Book(title:"The Shining")
b.properties = this.params



Methods

add

Description

Adds a domain class relationship to a specific one-to-many or many-to-many relationship.

Parameters 
  • to -  specifies the hasMany relationship name to which the object is being added
Example
def a = new Author(name:"Stephen King")
             .add(to:"fiction",
                   new Book(title:"IT"))
             .add(to:"non-fiction",
                   new Book(title:"On Writing: A Memoir of the Craft"))
             .save()



add* (deprecated)

Description 

Deprecated since 0.5 Use addTo* instead.

Adds a domain class relationship for one-to-many or many-to-many relationship, where the relationship is indicated by the class used as the suffix to the method.

Example
def a = new Author(name:"Stephen King")
             .addBook(new Book(title:"IT"))
             .addBook(new Book(title:"The Stand"))
             .save()



addTo*

Description 

Adds a domain class relationship for one-to-many or many-to-many relationship, where the relationship is indicated by the property used as the suffix to the method.

Example
def fictBook = new Book(title:"IT")
def nonFictBook = new Book(title:"On Writing: A Memoir of the Craft")
def a = new Author(name:"Stephen King")
             .addToFiction(fictBook)       // 'fiction' is name of relationship property
             .addToNonFiction(nonFictBook) // 'nonFiction' is name of relationship property
             .save()



delete

Description

Deletes a domain class instance from the database

Example
def b = Book.get(1)
b.delete()



discard

Description

Discards any changes that have been made during an update. Note that this method will not clean or reset the object with the original values it will just prevent it from being automatically saved by Grails.

Example
def b = Book.get(1)
b.title = "Blah"
b.discard() // changes won't be applied now



hasErrors

Description

True if the domain class instance has errors following a call to "validate" or "save"

Example
def b = new Book(title:"The Shining")
b.validate()
if(b.hasErrors()) {
    b.errors.each {
          println it
    }
}



ident

Description

Returns the value of the identity property of the domain class regardless of the name of the identity property itself

Example
def b = new Book(title:"The Shining")
b.save()

println b.ident()



merge

Description

see Hibernate3's merge

refresh

Description

Refreshes a domain classes state from the database

Example
def b = Book.get(1)
b.refresh()



save

Description

Saves a domain class instance to the database cascading updates to any child instances if required. Returns false if validation failed and the instance was not saved

Parameters
  • validate (optional) - Set to false if validation should be skipped
Example
def b = new Book(title:"The Shining")
if( !b.save() ) {
   b.errors.each {
        println it
   }
}



validate

Description

Validates a domain class against the applied constraints (see Validation)

Example
def b = new Book(title:"The Shining")
if( !b.validate() ) {
   b.errors.each {
        println it
   }
}



Static Methods

count

Description

Counts the number of instances in the database and returns the result

Parameters

None

Example
def noOfBooks = Book.count()



countBy

Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that count the number of records returned

Examples
Book Domain Class
class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
Examples
def c = Book.countByTitle("The Shining")
c = Book.countByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
c = Book.countByReleaseDateBetween(firstDate, new Date())
c = Book.countByReleaseDateGreaterThanEquals(firstDate)
c = Book.countByTitleLike("%Hobbit%")
c = Book.countByTitleNotEqual("Harry Potter")
c = Book.countByReleaseDateIsNull()
c = Book.countByReleaseDateIsNotNull()

see also OperatorNamesInDynamicMethods

createCriteria

Description

Creates a grails.orm.HibernateCriteriaBuilder instance for the domain class. (see Builders)

Example
def c = Account.createCriteria()
def results = c {
	like("holderFirstName", "Fred%")
	and {
              between("balance", 500, 1000)
              eq("branch", "London")
	}
	maxResults(10)
	order("holderLastName", "desc")
}



exists

Description

Checks whether an instance exists for the specified id and returns true if it does

Parameters
  • id (required) - The id of the instance
Example
if(Account.exists(1)) {
     // do something
}



executeQuery

some old forms of this method (like executeQuery(String query, Object[] positionalParams)) are deprecated as of 0.6, use one of the forms listed below instead
Description

Allows the execution of HQL queries against a domain class

Syntax
Book.executeQuery( String query )
Book.executeQuery( String query, Collection positionalParams )
Book.executeQuery( String query, Collection positionalParams, Map paginateParams )
Book.executeQuery( String query, Map namedParams )
Book.executeQuery( String query, Map namedParams, Map paginateParams )
Parameters
  • query - An HQL query
  • positionalParams - A List of parameters for a positional parametrized HQL query
  • namedParams - A Map of named parameters a HQL query
  • paginateParams - A Map containing parameters 'max' or/and 'offset' (see examples below)
Example
// simple query
Account.executeQuery( "select distinct a.number from Account a" );
// using with list of parameters
Account.executeQuery( "select distinct a.number from Account a where a.branch = ? and a.created > ?", ['London',lastMonth] );
// using with a single parameter and pagination params (since 0.5)
Account.executeQuery( "select distinct a.number from Account a where a.branch = ?", ['London'], [max:10,offset:5] );
// using with Map of named parameters (since 0.5)
Account.executeQuery( "select distinct a.number from Account a where a.branch = :branch", [branch:'London'] );
// using with Map of named parameters and pagination params (since 0.5)
Account.executeQuery( "select distinct a.number from Account a where a.branch = :branch", [branch:'London', max:10, offset:5] );
// same as previous
Account.executeQuery( "select distinct a.number from Account a where a.branch = :branch", [branch:'London'], [max:10, offset:5] );



executeUpdate

Description

Allows updating a database with DML-style operation

Syntax
Book.executeUpdate( String query )
Book.executeUpdate( String query, Collection positionalParams )
Parameters
  • query - An HQL query with DML-style operations
  • positionalParams - A List of parameters for a positional parametrized HQL query
Example
Account.executeUpdate("delete Book b where b.pages > 100")
Account.executeUpdate("delete Book b where b.title like ?", ['Groovy In Action'])
Account.executeUpdate("delete Book b where b.author=?", [Author.get(1)])
Account.executeUpdate("update Book b set b.title='Groovy In Action' where b.title='GINA'")



find

Description

Finds and returns the first result for the given query or null if no instance was found

Syntax
Book.find( String query )
Book.find( String query, Collection positionalParams )
Book.find( String query, Map namedParams )
Book.find( Book example )
Parameters
  • query - An HQL query
  • positionalParams - A List of parameters for a positional parametrized HQL query
  • namedParams - A Map of named parameters a HQL query
  • example - An instance of the domain class for query by example
Example
// Dan brown's first book
Book.find("from Book as b where b.author='Dan Brown'")
// with a positional parameter
Book.find("from Book as b where b.author=?",['Dan Brown'])
// with a named parameter (since 0.5)
Book.find("from Book as b where b.author=:author",[author:'Dan Brown'])

def b = new Book(author:"Dan Brown")
Book.find(b) // query by example



findAll

Description

Finds all of the domain class instances for the specified query

Syntax
Book.findAll()
Book.findAll( String query )
Book.findAll( String query, Collection positionalParams )
Book.findAll( String query, Collection positionalParams, Map paginateParams )
Book.findAll( String query, Map namedParams )
Book.findAll( String query, Map namedParams, Map paginateParams )
Book.findAll( Book example )
Parameters
  • query - An HQL query
  • positionalParams - A List of parameters for a positional parametrized HQL query
  • namedParams - A Map of named parameters a HQL query
  • paginateParams - A Map containing parameters 'max' or/and 'offset' (see examples below)
  • example - An instance of the domain class for query by example
Examples
// everything
Book.findAll()
// with a positional parameter
Book.findAll("from Book as b where b.author=?",['Dan Brown'])
// 10 books from Dan Brown staring from 5th book ordered by release date
Book.findAll("from Book as b where b.author=? order by b.releaseDate",['Dan Brown'],[max:10,offset:5])

// examples with max/offset usage
def query = "from Book as b where b.author='Dan Brown' order by b.releaseDate"
// first 10 books
Book.findAll(query,[max:10])
// 10 books starting from 5th
Book.findAll(query,[max:10,offset:5])

// examples with named parameters (since 0.5)
Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'])
Book.findAll("from Book as b where b.author=:author", [author:'Dan Brown'], [max:10, offset:5])
Book.findAll("from Book as b where b.author in (:authors)", [authors:['Dan Brown','Jack London']])

// examples with tables join
Book.findAll("from Book as b where not exists (from Borrow as br where br.book = b)")

// query by example
def b = new Book(author:"Dan Brown")
Book.findAll(b)



findBy

Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return the first result of the query

Examples
Book Domain Class
class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
Examples
def b = Book.findByTitle("The Shining")
b = Book.findByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
b = Book.findByReleaseDateBetween(firstDate, new Date())
b = Book.findByReleaseDateGreaterThanEquals(firstDate)
b = Book.findByReleaseDateLessThanEquals(firstDate)
b = Book.findByTitleLike("%Hobbit%")
b = Book.findByTitleIlike("%Hobbit%") // (since 0.5) - ignorecase
b = Book.findByTitleNotEqual("Harry Potter")
b = Book.findByReleaseDateIsNull()
b = Book.findByReleaseDateIsNotNull()

see also OperatorNamesInDynamicMethods

findAllBy

Description

Dynamic method that uses the properties of the domain class to allow the creation of Grails query method expressions that return all instances of the domain class

Examples
Book Domain Class
class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
Examples
def results = Book.findAllByTitle("The Shining", [max:10, sort:"title", order:"desc", offset:100] )
results = Book.findAllByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
results = Book.findAllByReleaseDateBetween(firstDate, new Date())
results = Book.findAllByReleaseDateGreaterThanEquals(firstDate)
results = Book.findAllByTitleLike("%Hobbit%")
results = Book.findAllByTitleIlike("%Hobbit%") // (since 0.5) - ignorecase
results = Book.findAllByTitleNotEqual("Harry Potter")
results = Book.findAllByReleaseDateIsNull()
results = Book.findAllByReleaseDateIsNotNull()

see also OperatorNamesInDynamicMethods

findWhere

Description

Uses named arguments that match the property names of the domain class to produce a query that returns the first result.

Examples
Book Domain Class
class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
Examples
def b = Book.findWhere(title:"The Shining", author:"Stephen King")



findAllWhere

Description

Uses named arguments that match the property names of the domain class to produce a query that returns all of the matching results.

Examples
Book Domain Class
class Book {
   Long id
   Long version
   String title
   Date releaseDate
   String author
}
Examples
def books = Book.findAllWhere(author:"Stephen King")



get

Description

Retrieves an instance of the domain class for the specified id, otherwise returns null

Examples
def b = Book.get(1)



getAll

Description

(Since 0.5) Retrieves an instances of the domain class for the specified ids and returns a list of these instances, ordered by the original ids list. If some of provided ids are null or there are no instances with these ids, then result list will contain null values on corresponding positions.

Examples
// get a list which contains Book instances with ids 2, 1, 3 respectively
def bookList = Book.getAll(2,1,3)
// can take a list of ids as only argument, extremely useful when ids list calculated in code
def bookList = Book.getAll([1,2,3])
// when called without arguments returns list of all objects
def bookList = Book.getAll()



list

Description

Lists all of the instances of the domain class.

Parameters
  • max - The maximum number to list
  • offset - The offset from the first result to list from
  • order - The order to list by, either "desc" or "asc"
  • sort - The property name to sort by
Examples
// list everything
def results = Book.list()
// list 10 results
def results = Book.list(max:10)
// list 10 results, offset by 100
def results = Book.list(max:10, offset:100)
// list 10 results, offset by 100, orderd by title in descending order
def results = Book.list(max:10, offset:100, sort:"title", order:"desc")



listOrderBy

Description

Lists all of the instances of the domain class ordered by the property in the method expression

Parameters
  • max - The maximum number to list
Examples
def results = Book.listOrderByAuthor() // everything
def results = Book.listOrderByTitle(max:10) // 10 results
def results = Book.listOrderByTitle(max:10, offset:100, order:"desc") // 10 results, offset from 100



withCriteria

Description

Allows inline execution of criteria with a closure. (Since 0.4)

Parameters
  • arguments (optional) - A map on named arguments that will be set on the criteria instance
  • closure - A closure that defines the criteria
Examples
def results = Book.withCriteria {
    def now = new Date()
    between('releaseDate', now-7, now)
    like('title', '%Groovy%')
}



withTransaction

Description

Uses Spring's TransactionTemplate combination with a closure. Since 0.4

Parameters
  • closure - A closure that gets passed an instance of the Spring TransactionStatus to allow programmatic management of savepoints (See SavepointManager) and transaction rollback
Examples
Book.withTransaction { tx ->
    def b = new Book(title:"Groovy in Action")

    b.save()

    // some logic that goes wrong
    tx.setRollbackOnly()

}

Labels

 
(None)