"Fossies" - the Fresh Open Source Software Archive

Member "grails-core-5.2.4/grails-docs/src/test/resources/docs/ref/Domain Classes/findOrSaveBy.html" (14 Sep 2022, 62107 Bytes) of package /linux/www/grails-core-5.2.4.tar.gz:

Caution: In this restricted "Fossies" environment the current HTML page may not be correctly presentated and may have some non-functional links. You can here alternatively try to browse the pure source code or just view or download the uninterpreted raw source code. If the rendering is insufficient you may try to find and view the page on the grails-core-5.2.4.tar.gz project site itself.

(Quick Reference)



Dynamic method that uses the properties of the domain class to create query method expressions that return the first result of the query. This method behaves like findBy except that it will never return null. If a matching instance cannot be found then a new instance will be created, populated with values represented in the query parameters, saved and returned. The difference between this method and findOrCreateBy is that this method will save any newly created instance where findOrCreateBy does not.


Given the domain class Book:

class Book {
   String title
   String author

The following are all possible:

def b = Book.findOrSaveByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")

The following are roughly equivalent:

def b = Book.findOrSaveByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
def b = Book.findByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
if (!b) {
    b = new Book(title: "The Sum of All Fears", author: "Tom Clancy")


GORM supports the notion of Dynamic Finders. The findOrSaveBy* 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.findOrSaveByTitle(authorValue) is valid but Book.findOrSaveByAuthorInList(listOfNames) is not.