////
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
////


== findOrSaveBy*



=== Purpose


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 link:{domainClassesRefFromRef}findBy.html[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 link:{domainClassesRefFromRef}findOrCreateBy.html[findOrCreateBy] is that this method will save any newly created instance where link:{domainClassesRefFromRef}findOrCreateBy.html[findOrCreateBy] does not.


=== Examples


Given the domain class `Book`:

[source,groovy]
----
class Book {
   String title
   String author
}
----

The following are all possible:

[source,groovy]
----
def b = Book.findOrSaveByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
----

The following are roughly equivalent:

[source,groovy]
----
def b = Book.findOrSaveByTitleAndAuthor("The Sum of All Fears", "Tom Clancy")
----

[source,groovy]
----
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")
    b.save()
}
----


=== Description


GORM supports the notion of  link:{hibernate5GuideFromRef}index.html#finders[Dynamic Finders]. The `findOrSaveBy*` method finds the first result for the given method expression.

NOTE: 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.
