5

I have 2 tables in grails with mysql

say A and B

The scenarios that I want to implement here are :

(1)instance of A can have zero / one / more than one instance of B.

(2)when instance A is deleted then all its related Bs must be deleted.

(3)each instance of B must be associated with only one instance of A.

(4)A knows about B , but B does not know about A.

condition number 4 is not mandatory.

From the above info it seems like : unidirectional one to many from A to B

Currently what I am doing is: (taking help from here )

class A
{
  String name
  Set bs=[]
  static hasMany=[bs:B]
}

Class B
{
  String name
}

B b=new B(name:'bname')
b.save()
A a=new A(name:'aname')
a.addToBs(b)
a.save()

While saving both entries,(B is saving but A is not saving) I am using addTo and getting error no signature of the method addToBs()

Please help me and also correct me if I am wrong somewhere.

1 Answer 1

8
class A
{
  String name
  static hasMany=[bs:B] //by default bs are Set. no need of explicit declaration
}

Class B
{
  String name
  static belongsTo = A //when delete a it's b also will get deleted
}

    B b1=new B(name:'bname1')
    B b2=new B(name:'bname11')
    B b3=new B(name:'bname2')
    A a=new A(name:'aname1')
    A a2=new A(name:'aname2')
    a.save(flush:true)
    a2.save(flush:true)
    a.addToBs(b1)
    a.addToBs(b2)
    a2.addToBs(b3)
    a.save(flush:true)
    a2.save(flush:true)

No need of save the instance of b. When we add the b instance into the collection of b's on a, it will automatically save the instance of b when we save the instance of a.

3
  • what if you don't have the belongsto relationship? i'm having a similar problem where if i save A after adding it to the hasmany list the list doesn't get updated. i can't have a belongsto because my class B could beelong to 2 different classes and i don't want those 2 classes to be linked in any way (ie: inheritence)
    – Randyaa
    Dec 9, 2015 at 22:51
  • @Randyaa You can always use interface, which both of these classes implement, and which will be an owner of these classes (they belongs to implementations of this interface). Feb 22, 2016 at 14:41
  • Is it absolutely necessary to perform flush for b's to be added to a? Jan 7, 2018 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.