Skip to content

Commit

Permalink
updated docs on one-to-one mappings
Browse files Browse the repository at this point in the history
  • Loading branch information
graemerocher committed Jul 23, 2009
1 parent 4617df2 commit 1ec4733
Showing 1 changed file with 11 additions and 26 deletions.
37 changes: 11 additions & 26 deletions grails-doc/src/guide/5.2.1.1 One-to-one.gdoc
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -10,24 +10,22 @@ class Nose {
} }
{code} {code}


In this case we have unidirectional one-to-one relationship from @Face@ to @Nose@. To make this relationship bidirectional define the other side as follows: In this case we have unidirectional many-to-one relationship from @Face@ to @Nose@. To make it a true one-to-one you should make @nose@ unique:

h5. Example B


{code} {code}
class Face { class Face {
Nose nose Nose nose
static constraints = {
nose unique:true
}
} }
class Nose { class Nose {
Face face
} }
{code} {code}


This is bidirectional relationship. However, in this case no updates are cascading from either side of the relationship. To make this relationship bidirectional define the other side as follows:

Consider this variation:


h5. Example C h5. Example B


{code} {code}
class Face { class Face {
Expand Down Expand Up @@ -58,30 +56,17 @@ def f = Face.get(1)
f.delete() // both Face and Nose deleted f.delete() // both Face and Nose deleted
{code} {code}


Without @belongsTo@ deletes would *not* be cascading and you would get a foreign key constraint error unless you explicitly deleted the Nose: In the previous example the foreign key associated the @Face@ with the @Nose@ is stored in the parent as column called @nose_id@. If you want the foreign key to be stored in the child you need a @hasOne@ association:
{code}
// error here without belongsTo
def f = Face.get(1)
f.delete()

// no error as we explicitly delete both
def f = Face.get(1)
f.nose.delete()
f.delete()
{code}


You could keep the previous relationship as unidirectional and allow saves/updates to cascade down by doing the following: h5. Example C


{code} {code}
class Face { class Face {
Nose nose static hasOne = [nose:Nose]
} }
class Nose { class Nose {
static belongsTo = Face Face face
} }
{code} {code}


Note in this case because we are not using the map syntax in the @belongsTo@ declaration and explicitly naming the association. Grails will assume it is unidirectional. The diagram below summarizes the 3 examples: In this example you get a bidirectional one-to-one where the foreign key column is stored in the @nose@ table inside a column called @face_id@.


!GORM-1to1.png!

0 comments on commit 1ec4733

Please sign in to comment.