////
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.
////
[[gormAssociation-oneToMany]]
== One-to-Many Associations

A one-to-many association is declared using `hasMany`. It represents a collection of associated domain objects.

=== Bidirectional One-to-Many

When both sides declare the relationship, GORM manages the foreign key on the many side's table:

[source,groovy]
----
class Author {
    String name
    static hasMany = [books: Book]  // <1>
}

class Book {
    String title
    Author author                   // <2>
    static belongsTo = [author: Author]
}
----
<1> `Author` owns a collection of `Book` objects.
<2> `Book` declares the back-reference. `belongsTo` also enables cascade delete.

With `belongsTo`, deleting an `Author` will cascade-delete all of its `books`.

=== Unidirectional One-to-Many

Without `belongsTo` on the other side, GORM uses a join table to maintain the relationship:

[source,groovy]
----
class Author {
    String name
    static hasMany = [books: Book]
}

class Book {
    String title
    // no belongsTo or author property
}
----

The join table name defaults to `author_books` and can be customised — see xref:ormdsl-tableAndColumnNames[Table and Column Names].

=== Sorting

You can define a default sort order for the collection:

[source,groovy]
----
class Author {
    static hasMany = [books: Book]
    static mapping = {
        books sort: 'title', order: 'asc'
    }
}
----

=== Adding and Removing Items

[source,groovy]
----
def author = Author.get(1)
author.addToBooks(new Book(title: 'Groovy in Action'))
author.save()

author.removeFromBooks(author.books.first())
author.save()
----
