---
title: "grails belongsTo使用"
author: "小于Brick"
date: "2016-10-14T17:32:18Z"
tags: ["外键", "多对一"]
categories: ["编程语言"]
slug: "grails-belongsto"
draft: false
lastmod: "2016-10-14T18:59:59Z"
id: 2330645
url: "https://youngbrick.iteye.com/blog/2330645"
---

grails3 belongsTo，多对一关系

参考：http://docs.grails.org/latest/ref/Domain%20Classes/belongsTo.html

 

对象说明：

作者：Author

书：Book

Book 属于 Author

 

 

```
static belongsTo 
有两种使用方式：
```

```
方式一：
static belongsTo = Author //[Domain1,Domain2]
这种方式不存在引用，数据库不会建立索引和外键的。
感觉是没有什么用，但是在多对多中是必须要指定的，否则异常。

domain:
```

```
class Author {
    String name
    static constraints = {
    }
}
```

```

```

```
class Book {
    static belongsTo = Author
    String title
    static constraints = {
    }
}
```

```


数据库：




页面：





========================================================================================
```

```
方式二：
static belongsTo = [author:Author]//[doamin:Domain1,domain2:Domain2]
或者：
Author author
static belongsTo = Author

这种方式数据库Book表会建立Author的索引和外键（author_id）

```

```
doamin:

```

```
class Author {
    String name
    static constraints = {
    }
}
```

```
class Book {
    static belongsTo = [author: Author]
    String title
    static constraints = {
    }
}
```

```
数据库：
```

![](http://dl.iteye.com/upload/picture/pic/136251/41608afd-c0b5-39a2-b722-23442847996c.jpg)

```
页面：
```

![](http://dl.iteye.com/upload/picture/pic/136253/2b1b2ad2-64b6-36d9-a034-eb614dc414c7.jpg)

```
在页面中添加了author字段，可以用于book与author的关系维护。


```