【问题标题】:Grails Many-to-Many Relationship with a domain which has String id columnGrails 与具有 String id 列的域的多对多关系
【发布时间】:2016-12-05 15:22:59
【问题描述】:

如何与id列为字符串的域建立多对多关系?

UnitObj 值示例有:'0'、'1'、'001'、'002'、'1234' 等。 因此,由于这些值,我无法使 id 列(UnitObj 中的值列)longinteger

任何帮助将不胜感激。 以下是域:

class UnitObj {
    String value
    String unit
    UnitObj parent

    static constraints = {
        value(unique: true, nullable: false)
        unit(nullable: false)
        parent(nullable: true)
    }

    static mapping = {
        version false
        id generator: 'assigned', name: "value", type: 'string'
        table name: "unit_obj", schema: "db"
    }
}

这是我要更改的。

class UserUnitObj {
    User user
    String unit  //This should be UnitObj not string
    String subUnit //This should be UnitObj not string

    static constraints = {
       user(nullable: false)
       unit(nullable: false)
       subUnit(nullable: true)
    }
    static mapping = {
       version false
       table name: "user_unit_obj", schema: "db"
    }
}

---------编辑--------

如果我将字符串更改为 UnitObj,则在尝试创建 UserUnitObj 时会给出:

  UserUnitObj u = new UserUnitObj()
  u.user = User.get(userUnitJson.user)
  u.unit = UnitObj.findByValue(userUnitJson.unit.id.toString())
  u.subUnit = UnitObj.findByValue(userUnitJson.subUnit.id.toString())
  u.save(flush: true)

这是错误:

2016-12-05 17:51:14,305 [http-bio-8080-exec-4] ERROR spi.SqlExceptionHelper  - ERROR: column "sub_unit_id" is of type bigint but expression is of type character varying

Hint: You will need to rewrite or cast the expression.
  Position: 79
Error |
org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not execute statement; bad SQL grammar [n/a]; nested exception is org.postgresql.util.PSQLException: ERROR: column "sub_unit_id" is of type bigint but expression is of type character varying
  Hint: You will need to rewrite or cast the expression.

【问题讨论】:

  • 如果将这些字符串更改为 UnitObj 实例,会发生什么?
  • @Gregg 我编辑了帖子

标签: grails many-to-many grails-orm


【解决方案1】:

问题不在于您将String 用于分配的ID。问题是因为您没有告诉UserUnitObj 您使用的是value 而不是id。默认情况下,GORM 将始终将FK 分配给名为id 的列。如果你做一些不同的事情,你必须告诉它。有关如何执行此操作的说明,请参阅 documentation here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-30
    • 2023-03-18
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多