【问题标题】:how can i add a integer list in grails domain class如何在 grails 域类中添加整数列表
【发布时间】:2014-06-25 12:48:59
【问题描述】:

我创建了一个如下所示的域类,其中包含一个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 域类中添加整数列表。

【问题讨论】:

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


    【解决方案1】:

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

    class User {
    
        int userId
    
        static hasMany = [userFriendsIds: Integer]
    
        static mapping = {
            userFriendsIds joinTable: [name: "user_id", column: "friend_id", type: Integer]
        }
    
        static constraints = {
        }
    
        User() {
        }
    }
    

    【讨论】:

    • 我尝试了这种方法但不起作用..在这种情况下..但在字符串列表的情况下有效
    • 我更新了示例以使用 joinTable 映射,以确保映射不使用保留的列名。
    • 您还应该注意属性名称 userIduserFriendsId 以小写字母而不是大写字母开头。
    • 我也尝试过映射...比如 userFriendsIds joinTable: [name: "user_id", column: "user_friends_ids", type: Integer] 但它不起作用。
    • 能否为数据源开启 SQL 日志记录?在grails.org/doc/2.2.1/guide/conf.html#dataSource看logSql
    【解决方案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 ...
    }
    

    【讨论】:

    • 所以我们不能在 grails 域类中保存整数列表?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多