Reputation: 4004
I hava Java/JavaEE background and started a Grails project recently.
When I write the domain model, there is a requirement: unidirectional many-to-many. I know how it should be in Jpa/Hibernate. I had a quick search about that in grails and seems it is not supported in Grails and some people suggest using a mapping class (there is no example how should do).
Anyone can give me an example of that or how I should do for this requirement?
For example:
class Teacher {
static hasMany: [students: Student]
}
class Student {
static belongsTo: Teacher
static hasMany: [teachers: Teacher]
}
Above code is done using a bi-directional many-to-many in Grails documents. What's the code like for a uni-directional many-to-many?
Also only student can have a teachers reference, in teacher class, it can't get a list of students.
Thanks.
Upvotes: 1
Views: 908
Reputation: 1
Unidirectional many-to-many relationships is supported by hibernate and possible with Grails:
http://blog.exensio.de/2013/12/unidirectional-many-to-many.html
Upvotes: 0
Reputation: 983
I have used three classes like teacher,student, and intermediate class stuteach.From student we can access teachers reference.In teacher side,we cant access students.
class Teacher {
String name
}
class Student {
String name
static hasMany = [teachers:StuTeach]
}
class StuTeach {
static constraints = {
}
static belongsTo = [teacher:Teacher,student:Student]
}
In bootstrap,
def t1=new Teacher(name:"t1")
t1.save(flush:true)
def t2=new Teacher(name:"t2")
t2.save(flush:true)
def stu=new Student(name:"s1")
stu.save(flush:true)
def stuteach1=new StuTeach()
stuteach1.student=stu
stuteach1.teacher=t1
stuteach1.save(flush:true)
def stuteach2=new StuTeach()
stuteach2.student=stu
stuteach2.teacher=t2
stuteach2.save(flush:true)
stu.addToTeachers(stuteach1)
stu.addToTeachers(stuteach2)
stu.save(flush:true)
println stu.teachers.teacher
Upvotes: 1