grails bidirectional relationship in abstract classes -
i trying define grails domain model abstract classes. need define 2 abstract classes have one-to-one bidirectional relationship each other , can't bring them work.
explanation based on face-nose example of documentation:
i implemented example , wrote test works expected: if set end of relationship, grails sets other end.
class face { static hasone = [nose:nose] static constraints = { nose nullable: true, unique:true } } class nose { face face static belongsto = [face] static constraints = { face nullable:true } } when:'set nose on face' def testface = new face().save() def testnose = new nose().save() testface.nose = testnose testface.save() then: 'bidirectional relationship' testface.nose == testnose testnose.face == testface if declare these 2 classes abstract , repeat same test 2 concrete subclasses (concreteface , concretenose without attribute), second assertion false: testnose.face null.
am doing somthing wrong? if not, how can factorize relationships in abstract domain classes?
you have more save()'s needed, , logic inside nose wrong. first, face class is; let's paste here completion:
class face { static hasone = [nose:nose] static constraints = { nose nullable:true, unique: true } } next, nose:
class nose { static belongsto = [face:face] static constraints = { } } note here once have belongsto relationship, can't have face -- parent -- nullable in constraints section.
last, integration test. make sure it's integration test , not unit test. integration testing needed when you're testing database-related logic (crud ops), not mocking ops unit tests do. here:
def "test bidirectionality integration"() { given: "a fresh face , nose" def face = new face() def nose = new nose(face:face) face.setnose(nose) when: "the fresh organs saved" face.save() then: "bidirectionality achieved" face.nose == nose nose.face == face } note here save nose not needed, saving face persists nose. may add statement nose.save() after face.save() give nothing here, not before -- can't save child before it's parent nicely settled in tables.
do , 'll 1 of these:
|tests passed - view reports in ...
Comments
Post a Comment