grails中的多对多关系

Many to Many relationship in grails

我正在尝试 grails/Gorm 中的多对多关系示例。下面是我尝试过的代码 far.When 我正在尝试分析一个不同的场景我想知道 Gorm 休眠是如何处理它的。

 class Author {
   static hasMany = [books:Book]
   String name
 }

 class Book {
   static belongsTo = Author
   static hasMany = [authors:Author]
   String title
 }

 And in my controller i defined this way in order to add Authors and books.

 def a=new A(name:"ABC")
 def b=new B(title:"Code1")
 a.addToB(b)  
 def a=new A(name:"ABC")
 def b=new B(title:"Code2")
 a.addToB(b)         //It works.

 In the databaselevel it creates

 Table Author        Table Author-Book        Table Book
 id name               id   id                 id    Book
 1  ABC                1     1                 1     Code1
 2  ABC                2     2                 2     Code2

But what i want is the below format:

Table Author        Table Author-Book        Table Book
 id name               id   id                 id    Book
 1  ABC                1     1                 1     Code1
                       1     2                 2     Code2

当我将作者姓名设置为唯一时,如何实现这一点?

您的域设置很好。您正在明确创建两位作者(同名)。我会将您的代码更改为

def a=new A(name:"ABC")
 def b=new B(title:"Code1")
 a.addToB(b)  
 def a= A.findOrSaveByName("ABC")       // this will attempt to query the db first and only create new record it already doesn't exist
 def b=new B(title:"Code2")
 a.addToB(b)         //It works.