【问题标题】:Grails domain mapping of legacy tables that share same primary key name共享相同主键名称的旧表的 Grails 域映射
【发布时间】:2021-07-23 18:23:17
【问题描述】:

旧数据库有两个表,它们使用相同的列名作为主键。例如:

用户:
user_id int
名称字符串

用户个人资料:
user_id int
visit_count int

我想创建一个双向的一对一关系。即

class User {
    String name
    UserProfile userProfile
    static mapping = {
        id column: 'user_id'
    }
}

class UserProfile {
    Integer visitCount
    User user
    static mapping = {
        id column: 'user_id'
    }
}

我希望能够引用“user.userProfile.visitCount”或“userProfile.user.name”。

我尝试了许多直接引用和关系描述符的组合,“hasOne”、“belongsTo”等。我认为这很简单,但找不到正确的语法。我收到重复的列问题或缺少列名的问题。任何帮助,将不胜感激。提前致谢。

【问题讨论】:

标签: hibernate grails grails-orm one-to-one grails-domain-class


【解决方案1】:

UserProfile 中的用户默认为 user_id,与 UserProfile 的 id 列相同。因此,只需为用户引用添加一个列名,如下所示。

class UserProfile {
    Integer visitCount
    User user

    static mapping = {
        id column: 'user_id'
        user column: 'useruser_id'
    }
}

class User {
    String name

    static mapping = {
        id column: 'user_id'
    }

    static hasOne = [ userProfile: UserProfile ]
}

【讨论】:

  • 是否需要userProfile column: 'userProfile_id'
  • 引起:org.hibernate.MappingException:实体映射中的重复列:dommaping.UserProfile 列:org.hibernate 的 user_id(应该使用 insert="false" update="false" 映射) .mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:830) 在 org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:848) 在 org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:870)
  • 将列映射添加到用户对象没有帮助仍然得到上述错误。现在将列标题添加到 userProfile 对象并解决了问题。
  • “现在将列标题添加到 userProfile 对象并解决了问题。” - 这对我来说没有意义。您对答案所做的编辑没有userProfile 的列标题(也不应该)。
  • 为什么在User 类中同时需要UserProfile userProfilestatic hasOne = [ userProfile: UserProfile ]
猜你喜欢
  • 2016-06-05
  • 2020-06-16
  • 2014-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-29
  • 2014-08-12
  • 1970-01-01
相关资源
最近更新 更多