在grails和postgresql中使用hasMany

时间:2010-11-15 10:04:06

标签: grails groovy

我有一个 postgresql 数据库,该数据库具有以下列结构:

Author
  id
  name

Book
  id
  name
  author_id

重写这些表的Groovy域类:

class Author {
   static hasMany = [ books : Book ]

   Integer id
   String name
}   

class Book {
   static belongsTo = Author

   Integer id
   Integer project_id
   String name
}

我的主要目标是从作者实例中获取图书清单。

author = Author.get( 1 ) // gets a author
author.books // must return a list of books. 

但这不起作用。有什么明显我做错了吗?

注意我有很多Ruby / Rails经验和zull Java / Groovy经验。

1 个答案:

答案 0 :(得分:2)

将您的Book课程更改为:

class Book {
   static belongsTo = [authors: Author]

   static mapping = {
       authors column: 'author_id'
   } 

   Integer id
   Integer project_id
   String name
}

如果你没有像那样指定mapping,GORM默认会创建一个JOIN表,而不是。{/ p>

(顺便说一下,域类自动提供了一个“虚拟”id属性(我认为类型为Long),在PostgreSQL中转换为bigint。没有必要指定它手动,但也不会造成伤害。)


编辑:根据提问者评论更新:

如果一本书真的只有一位作者,那么您需要在Book课程中说明:

Author author
static belongsTo = [author: Author]

static mapping = { author column: 'author_id' } 

可以找到关于一对多关系的GORM文档here