Search code examples
grailsgrails-orm

Does Grails / GORM permit relationships in separate java packages?


Grails 3 application -- I've been having trouble with a hasMany property in Grails not populating. I just realized that the owning class is in a different package from the owned class. Am I doing something silly by relating across package boundaries?

Basic example of what I'm doing and observing, in case that doesn't make sense:

Owning Domain Class:

package com.example.project

import com.example.project.configuration.ConfigFile

class MotherClass {
    String name
    static hasMany = [ configFiles: ConfigFile ]
}

Owned Domain Class:

package com.example.project.configuration

import com.example.project.*

class ConfigFile {
    String name
    MotherClass motherClass
}

In Bootstrap.groovy:

MotherClass motherClass = new MotherClass(name:"mother").save(failOnError: true)
new ConfigFile(name: "file1", motherClass: mother).save(failOnError: true)
new ConfigFile(name: "file1", motherClass: mother).save(failOnError: true)
assert motherClass.configFiles.size() > 0 #this assertion would fail

In a random service:

assert MotherClass.findByName("mother").configFiles.size() > 0 #this would fail too.

My assertion fails may be caused by some other issue I'm experiencing, but I wanted to verify that crossing package boundaries wasn't to blame.


Solution

  • If you didn't make a mistake in typing above, you are defining a 'motherClass' object but in ConfigFiles setting the motherClass to a 'mother' object.

    I assume that's not the case - then, I think you are not providing Grails with enough information about the owner-child relationship.

    Typically you would add the children to the owner class and save the owner class and let the saves cascade to children.

    MotherClass mother = new MotherClass(name:"mother")
    mother.addToConfigFiles(new ConfigFile(name: "file1", motherClass: mother))
    mother.addToConfigFiles(new ConfigFile(name: "file1", motherClass: mother))
    mother.save(failOnError: true)
    

    And ideally you should have belongsTo clause on the ConfigFile side - otherwise the deletes won't be cascaded. see: http://docs.grails.org/3.1.1/ref/Domain%20Classes/belongsTo.html