(Quick Reference)
findOrCreateBy*
Purpose
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.
This method behaves like
findBy except that it should never return null. If a matching instance cannot be found in the
database then a new instance is created, populated with values represented in the query parameters and returned. The difference between
this method and
findOrSaveBy is that this method will not save any newly created instance where
findOrSaveBy
does.
Examples
Given the domain class
Book:
class Book {
String title
String author
}The following are all possible:
def b = Book.findOrCreateByTitle("The Shining")
b = Book.findOrCreateByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
b = Book.findByAuthorInList(["Douglas Adams", "Hunter S. Thompson"])The following are roughly equivalent:
def b = Book.findOrCreateByTitle("The Shining")def b = Book.findByTitle("The Shining")
if(!b) {
b = new Book(title: "The Shining")
}Description
GORM supports the notion of
Dynamic Finders. The
findOrCreateBy* method finds the first result for the given method expression.
Because this method potentially creates a new instance and populates properties on that instance, only exact match criteria are allowed. For
example, Book.findOrCreateByDate(dateValue) is valid but Book.findOrCreateByDateGreaterThan(dateValue) is not.