0
votes

So I have a 1:1 relationship:

class Number1 {
    Number2 n2
}

class Number2 {
    belongsTo = [n2: Number2]
}

Now, I want to initialize n2 in class Number1 like:

class Number1 {
    Number2 n2 = New Number2(...).save()
}

But Grails is failing with hibernate exceptions. What's the best practice here for initializing a field with this relationship?

1

1 Answers

1
votes

I presume there is a mistake here. As your question state, a Number2 should belongsTo Number1, not itself:

belongsTo = [n1: Number1]

If you define Number2 belongsTo Number1, an object of Number2 will not be able to persist if it has no associated Number1 object. You must add Number2 object to some Number1 object first.

Do something like this in a controller:

def a = new Number1();
def b = new Number2();

b.addToN1(a)
...

You should check out GORM Gotchas series for more details. It will show how to avoid very common mistakes when doing with Grails persistence.