Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top