0

我是 Grails 和映射的新手,我有一些看起来像这样的东西。我有两个域类,我需要在它们之间建立关系,当关系完成时,不会对我的 PostgreSQL 数据库中的现有表进行任何更改。

class Insurance{

Integer id 
String osg_name
String osg_logo
String osg_email
String osg_link

static hasMany = [ insurancePackage: InsurancePackage]

static constraints = {

    id(blank: false)
    osg_name (blank: false, size: 0..155)
    osg_logo (size: 0..155)
    osg_email (blank: false, size: 0..100)
    osg_link (size: 0..155)
}



static mapping = {
    table name: "insurance", schema: "common"
    version false    
    id generator :'identity', column :'osg_id', type:'integer'

}

}

  class InsurancePackage{

    Integer id
    Integer osg_id
    String osgp_comment
    Integer tpo_id
    String osgp_link
    String osgp_label

    //static belongsTo = Insurance

    static belongsTo = [insurance: Insurance]

    static constraints = {

        id(blank: false)
        osg_id (blank: false)
        osgp_comment (blank: false, size: 0..500)
        tpo_id (blank: false,)
        osgp_link (blank: false, size: 0..155)
        osgp_label (blank: false, size: 0..10)
    }

    static mapping = {
        table name: "insurance_package", schema: 'common'
        version false
        id generator :'identity', column :'osgp_id', type:'integer'
    }

}

这是我得到的错误

Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - Unsuccessful: alter table revoco.insurance_package add column insurance_id int4 not null
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - ERROR: column "insurance_id " contains null values
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - Unsuccessful: alter table revoco.insurance_package add constraint FK684953517A89512C foreign key (insurance_id ) references revoco.insurance
| Error 2015-07-16 13:38:49,845 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - ERROR: column "insurance_id " referenced in foreign key constraint does not exist

所以我无法连接这两个表,我得到了同样的错误,出于某种原因,Grails 试图找到 insurance_id 但它没有在类中定义,他们试图改变我的表,我不希望这种情况发生。

4

1 回答 1

1

您将在 insurance_package 表中创建一个新列,该列包含保险表的外键。(hasMany 和 belongsTo --> 一对多)这里的问题是该列默认有一个 NOT NULL 约束,但表中似乎已经有数据。

现在的问题是:如何处理表中已经包含的数据。Grails 想要设置 NOT NULL 约束但不能因为已经存在并且因为您刚刚创建了列并且值是 NULL

根据您的用例,您有 3 个选项:

  1. 删除表中已包含的值(可能不需要)
  2. 进入您的数据库管理工具并为这些行设置外键,然后重新启动服务器。错误应该消失
  3. 将“InsurancePackage”对象中保险参考(belongsTo)的约束设置为可为空:true
于 2015-07-16T15:22:43.390 回答