Search code examples
grailsmodelassociationsgrails-ormshared

How do you set up a database schema when one object is shared by two or more in Grails?


I would really appreciate if you can help me with a problem or can show me better way to do it. So basically I have 3 models,

Class Person {
         String firstName
         String lastName
         ...
         Address personalAdd
}

Class Business {
        String businessName
        String BusinessType
        ....
        Address BusinessAdd
}

now this 2 models are sharing one common model,

Class Address {
        String Street
        String zip
        ...
}

Now when I save business or person, it still shows that Address.list().size() == 0 in unit-testing. When I explicitly save the object as,

address.save(flush: true)
new Business(... ... ..., address: address).save(flush:true)

it works fine, but then when I delete it doesn't get deleted either. I tried cascade 'all-delete-orphan' and 'delete', didn't work, I also tried,

Class Business {

      ....
      def beforeDelete() {
           Address.withNewSession {
            Address.load(address.id).delete()
        }
      }
     .....
}

But still no expected output! What should i do? to solve this problem?


Solution

  • Your properties aren't linked by any hasMany or belongsTo relationships and are therefore handled independently. And you can't set a belongsTo on an address anyway (it has different parents). So what are your options?

    You can keep the entitites separate (as you have them now) and handle the relationships manually (GORM events can help you there).

    You can embed the Address into both the Person and the Business class. If you need the addresses to be in their own tables though, that won't work.

    Or you can subclass Address and have for example:

    class BusinessAddress extends Address {
        static belongsTo = [ business: Business ]
    }
    

    .. and

    class PersonAddress extends Address {
        static belongsTo = [ person: Person ]
    }
    

    This way you would have only one table with addresses in the database.