Grails problem persisting data in join tables for many-to-many relationships
I am having problems persisting domain objects where I have a many-to-many relationship with a join table
class A{
String name
开发者_开发百科static hasMany = [bs:B]
}
class B{
String surname
static belongsTo=A
static hasMany=[as:A]
}
A a = new A(name:'Test')
B b = new B(surname:'user')
a.addToBs(b)
a.save(flush:true)
Then what I would expect to see is the following
Table A Table AB Table B
id name a_id b_id id surname
1 Test 1 1 1 User
However, the data only persists into table A.
Does anybody know what I am doing wrong ?
thanks
I have found this link which is shows a clear way of mapping many to many relationships
http://chrisbroadfoot.id.au/2008/07/19/many-to-many-relationship-mapping-with-gorm-grails
I still havent been able to get it working the way that I want to at the moment
I tried imitating your code and cascading works for me.
Class A:
package searcher
class A {
String name
static hasMany = [bs:B]
static constraints = {
}
public String toString() {
def s = "Name: $name\n Bs: "
bs.each {
s = "$s $it "
}
return s
}
}
Class B:
package searcher
class B {
String surname
static belongsTo = A
static hasMany = [as:A]
static constraints = {
}
}
Controller Source:
package searcher
class ManyController {
def ab = {
A a = new A(name:'Test')
B b = new B(surname:'user')
a.addToBs(b)
a.save(flush:true)
render A.list()
}
}
Produces output:
[Name: Test Bs: searcher.B : 1 ]
I didn't run into the problem you did, but I did have some initial trouble that was fixed by doing a grails clean
. Have you tried a variety of database configurations? I was just using an in memory hsqldb set to create-drop. If you're using a DBMS that I happen to have installed I'll try pointing it to another database and giving it a whirl.
精彩评论