////
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-manyToOneAndOneToOne]]
== Many-to-One and One-to-One Associations

=== Many-to-One

Declare a many-to-one association by adding a property of the target domain class type:

[source,groovy]
----
class Book {
    String title
    Author author           // <1>
}

class Author {
    String name
}
----
<1> A foreign key column `author_id` is added to the `book` table.

When combined with `belongsTo`, the association participates in cascade save/delete:

[source,groovy]
----
class Book {
    String title
    static belongsTo = [author: Author]     // <1>
}
----
<1> The `author` property is added implicitly; deleting `Author` cascades to `Book`.

=== One-to-One

A one-to-one association is also declared as a simple property, but each `Author` can only have one `Biography`:

[source,groovy]
----
class Author {
    String name
    Biography biography      // <1>
}

class Biography {
    String summary
    static belongsTo = [author: Author]
}
----
<1> A unique foreign key `biography_id` is added to `author`.

=== Configuring the Foreign Key Column

Override the foreign key column name in the `mapping` block:

[source,groovy]
----
class Book {
    String title
    Author author
    static mapping = {
        author column: 'fk_author'
    }
}
----

=== Nullable Associations

By default, GORM-managed foreign key columns are non-nullable. To allow null:

[source,groovy]
----
class Book {
    Author author

    static constraints = {
        author nullable: true
    }
}
----
