Grails域可能没有' id'吗? [英] Is it possible for a Grails Domain to have no 'id'?

查看:101
本文介绍了Grails域可能没有' id'吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以创建没有'id'的表?例如,这是我的域:

Is it possible to create a table that has no 'id'? For example, this is my domain:

class SnbrActVector {

    int nid
    String term
    double weight

    static mapping = {
        version false
        id generator: 'identity'
    }

    static constraints = {
    }
}

当我运行此SQL语句时,它失败:

When I run this SQL statement, it fails:

insert into snbr_act_vector values (5, 'term', 0.5)

我检查了表,并且'id'已经设置为自动递增.我在想,另一种选择是删除"id"本身.还是有其他解决方法?请假定不能更改给定的SQL语句.

I checked the table and 'id' is already set to autoincrement. I'm thinking that another option is to remove the 'id' itself. Or is there another workaround for this? Please assume that it is not an option to change the givent SQL statement.

推荐答案

Gorm需要一个id字段才能工作.您可以使用如下所示的瞬态变量来伪造分配的ID.获取器和设置器将nid字段映射到id字段.

Gorm requires an id field to work. You can fake an assigned id by using a transient variable like below. The getters and setters map the nid field to the id field.

使用此方法保存域对象时,您必须执行以下操作:

When saving a domain object using this method you have to do:

snbrActVectgor.save(insert:true)

因为grails认为非null id是一个持久实例.

because grails thinks a non-null id is a persistent instance.

class SnbrActVector {
    Integer id
    // nid is the actual primary key
    static transients = ['nid']
    void setNid(Integer nid) {
        id = nid
    }
    Integer getNid() {
        return nid
    }

    static mapping = {
        version false
        id generator:'assigned', column:'nid', type:'integer'
    }
}

这篇关于Grails域可能没有' id'吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆