【问题标题】:Grails generating error while altering a tableGrails 在更改表时生成错误
【发布时间】:2014-06-10 11:12:52
【问题描述】:

我正在尝试将一个已经存在的 PHP 应用程序移动到 grails 中。

我已经根据现有数据库创建了域,并且代码运行良好。

当我需要在我的域中添加额外的布尔字段时,就会出现问题。

我收到以下错误。

2014-06-10 16:24:54,146 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - Unsuccessful: alter table entry add expedite tinyint not null

Error |
2014-06-10 16:24:54,163 [localhost-startStop-1] ERROR hbm2ddl.SchemaUpdate  - ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column, or alternatively if none of the previous conditions are satisfied the table must be empty to allow addition of this column. Column 'expedite' cannot be added to non-empty table 'entry' because it does not satisfy these conditions.

我尝试在变量本身中指定默认值。

boolean expedite = false

我还尝试在静态映射中添加默认值,如下所示:

static mapping = {
    table 'entry'
    expedite defaultValue: false
    version false
}

但错误仍然出现。知道我哪里出错了吗?我正在使用 sql server 2012。

【问题讨论】:

  • 你可以使加速为空吗?如果你能做到这一点,添加下一个代码可能是解决方案:静态约束= {加速可空:真}
  • 我确实试过这个,但我仍然得到同样的错误。

标签: grails sql-server-2012 grails-orm grails-domain-class grails-2.3


【解决方案1】:

由于mysql默认将布尔字段映射为一位值,所以布尔字段的值不能为空。

通过以下方式手动更新现有记录:

update my_table set expedite = 0;

或者您可以使用 grails 数据库迁移插件为您生成迁移。

域类中的任何原始数据类型都会获得默认值,因此如果您定义了像 Boolean expedite 这样的新字段,那么它可以使用空值。

因此,请始终确保使用原始和非原始数据类型。

【讨论】:

  • 我的问题是我无法手动更新表格。我需要用gorm来做。即使使用非原始数据类型,这个问题也会继续存在。使用 sql server 2012 而不是 mysql 也会出现此问题。
【解决方案2】:

看起来 sql server 使用 0 和 1 而不是 TRUE/FALSE。这是你要找的吗?

https://forum.hibernate.org/viewtopic.php?f=1&t=996345

另一个人这样解决...

http://codexplo.wordpress.com/2012/06/21/mapping-a-boolean-with-hibernate/

看起来你只需要在你的域中创建一个方法来拦截和转换。

【讨论】:

    【解决方案3】:

    尝试使用类,而不是原始类型:布尔加速

    【讨论】:

    • 即使使用布尔类,我也会遇到同样的错误。这个问题只有使用sql server 2012才会出现,mysql中不会出现。
    • 该字段是否可能已在表中创建?并且您正在尝试映射它。如果是这样,请手动删除字段并让 grails 使用类声明再次为您创建字段。
    • 不,此字段不存在于任何其他表中。
    • 在 SQL Server 2005 上试过。得到了同样的异常。如果约束具有以下条件,则它可以工作:expedite(nullable : true)
    猜你喜欢
    • 2012-02-12
    • 2011-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 2015-08-17
    • 2012-07-01
    相关资源
    最近更新 更多