grails中的多对多关系

时间:2018-03-08 21:25:12

标签: java grails gorm

我正在尝试grails / Gorm中的多对多关系示例。下面是我到目前为止所尝试的代码。当我试图分析一个不同的场景时,我想知道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

当我将作者的名字设置为唯一时,我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:0)

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

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.