Search code examples
grailsgrails-ormrelationship

Grails hasOne unidirectional


Currently I'm having some trouble, creating an unidirectional relationship in Grails.

I have a class Toilet with an Attribute Address. This Address is a seperate class. The Address can - theoretically - still exist, if the Toilet-Object, which the Address is associated with, gets deleted. The toilet will stay, too, if the address gets deleted.

GORM's hasOne is not what i need, because it creates a bidirectional relation.

Defining an attribute of the type class only results in a non-persisted Address (despite it's own table) - that means, the association of the Address to the Toilet-Object doesn't exist

I'm not really familiar with these kinds of relationships, so I would really appreciate a solution or another way to accomplish my goal

Hope my problem is clear - if not comment, and I will try to add further explanations


Solution

  • Found the solution.

    What I left out, was the implemenation of an interface in the Toilet class.

    The problem was (as a reminder) that the relationship of the address within the toilet class wasn't saved to the database.

    This was a problem of the interface itself - in this interface, getters and setters were defined and had to be implemented (the way an interface works - obviously). The problem here was, that the setter of the Address-Attribute expected the Type IAddress.

    I overloaded the setter to also receive a parameter of the type Address.

    With this change, the relationship between Toilet and Address is saved correctly to the database - the ID of the Address is saved in the table of the Toilet.

    I think the definition of the setter is just a mistake (i have no influence on the interface), but with this workaround i can get it to work anyways

    Hope this explanation helps others too.