如何在grails域类中添加整数列表

时间:2014-06-25 12:49:00

标签: grails grails-2.0 grails-domain-class

我创建了一个域类,如下所示,其中包含int和整数属性列表。

class User {

    int UserId
    List<Integer> UserFriendsId 

    static constraints = {
    }

    User() {
        this.UserId = 21
        this.UserFriendsId=[1,2,3]
    }
}

保存时为此域类生成的表格如下

    mysql> select * from user;
+----+---------+---------------------+
| id | version | UserId              |
+----+---------+---------------------+
|  1 |       0 |                  21 |
|  2 |       0 |                  21 |
|  3 |       0 |                  21 |
+----+---------+---------------------+
3 rows in set (0.00 sec)
此表userFriendsId中未生成user

列(即:用于整数列表)。

那么如何解决这个问题或者可以在grails域类中添加整数列表。

2 个答案:

答案 0 :(得分:1)

UserFriendsId列表应该映射为GORM basic collection type,而不仅仅是User域类中的列表:

class User {

    int userId

    static hasMany = [userFriendsIds: Integer]

    static mapping = {
        userFriendsIds joinTable: [name: "user_id", column: "friend_id", type: Integer]
    }

    static constraints = {
    }

    User() {
    }
}

答案 1 :(得分:-2)

为什么不将UserFriendsId设为逗号分隔的字符串?

class User {

    int UserId
    String UserFriendsId 

    static constraints = {
    }

    User() {
        this.UserId = 21
        this.UserFriendsId = "1,2,3"
    }
}

然后:

for (userId in UserFriendsId.get(21).split(','))
{
    println userId.toInteger()
    /// Or do whatever ...
}