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

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

问题描述

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

  class SnbrActVector {

int nid
字符串期限
双重

静态映射= {
版本false
id生成器:​​'identity'
}

静态约束= {
}
}

当我运行这条SQL语句时, :

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

我检查了表格并将'id'设置为autoincrement。我在想另一种选择是删除'id'本身。还是有另一种解决方法呢?请假设它不是一个可以更改给定的SQL语句的选项。

解决方案

Gorm需要一个id字段才能工作。你可以使用像下面这样的瞬态变量来伪造一个指定的id。 getters和setters将nid字段映射到id字段。

使用此方法保存域对象时,您必须这样做:

  snbrActVectgor​​.save(insert:true)



<因为grails认为非null的id是一个持久化的实例。

  class SnbrActVector {
整数id
// nid是实际的主键
static transients = ['nid']
void setNid(Integer nid){
id = nid
}
Integer getNid(){
return nid
}

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


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 = {
    }
}

When I run this SQL statement, it fails:

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

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 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)

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天全站免登陆