PERSISTENCE OF COLLECTIONS OF BASIC TYPESを試す

grails-1.1の新機能を試す。hasManyにStringとか普通のクラスを指定する。

class Person {

    static constraints = {
           name()
           email()
    }

    static hasMany = [nickNames:String]
    String name
    String email      
}

このドメインクラスで、以下のテーブルが作られる。

mysql> desc person;
+---------+--------------+------+-----+---------+----------------+
| Field   | Type         | Null | Key | Default | Extra          |
+---------+--------------+------+-----+---------+----------------+
| id      | bigint(20)   | NO   | PRI | NULL    | auto_increment |
| version | bigint(20)   | NO   |     | NULL    |                |
| email   | varchar(255) | NO   |     | NULL    |                |
| name    | varchar(255) | NO   |     | NULL    |                |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)

mysql> desc person_nick_names;
+-------------------+--------------+------+-----+---------+-------+
| Field             | Type         | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+-------+
| person_id         | bigint(20)   | YES  | MUL | NULL    |       |
| nick_names_string | varchar(255) | YES  |     | NULL    |       |
+-------------------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
Person p = new Person()
p.name = "yuhei"
p.email = "example@example.com"
p.save()


p.nickNames = ["yuhei","yu","yuchan"]
p.save()
mysql> select * from person;
+----+---------+---------------------+-------+
| id | version | email               | name  |
+----+---------+---------------------+-------+
|  1 |       1 | example@example.com | yuhei |
+----+---------+---------------------+-------+
1 row in set (0.00 sec)

mysql> select * from person_nick_names;
+-----------+-------------------+
| person_id | nick_names_string |
+-----------+-------------------+
|         1 | yu                |
|         1 | yuhei             |
|         1 | yuchan            |
+-----------+-------------------+
3 rows in set (0.00 sec)