【问题标题】:Grails 3 hasOne nullability issueGrails 3 hasOne 可空性问题
【发布时间】:2016-10-03 17:56:44
【问题描述】:

在将现有应用程序从 Grails 2.5 迁移到 3.1 时,我遇到了双向一对一关系的奇怪问题。

想象一个带有 User 和 Employee 对象的简单模型。 User 代表通用用户帐户。并非所有用户都是员工,但所有员工都是用户。此外,员工有对经理、主管等的引用(也是用户实例)。用户是关系的拥有者。

class User {
  Employee employee

  static mappedBy = [employee: "user"]
  static hasOne = [employee: Employee]

  static constraints = {
    employee(nullable:true)
  }
}

class Employee {
  User user // represents employee's own account, a bi-directional one-to-one
  User supervisor // represents a supervisor

  static belongsTo = [user: User]

  static constraints = {
    user(unique:true)
    supervisor(nullable:true)
  }
}

升级到 Grails 3 后的问题是,在创建模式下,这会导致员工表的 supervisor_id 列生成为 NOT NULL,而在 Grails 2 中它可以为空(只有 user_id 不为空) )。

我使用 Grails 3.1.12 和 3.2.0 对此进行了测试,两者的行为相同。我在我的域类声明中做了什么愚蠢的事情吗?我尝试了多种映射来实现与 Grails 2.5 中相同的行为,但没有运气。在某些情况下,我什至在关系的双方都获得了一个外键......

【问题讨论】:

    标签: grails grails-orm


    【解决方案1】:

    我不知道为什么您的代码可以使用以前版本的 Grails,但这是错误的。

    当你使用hasManybelongsTo时,不需要在子对象中定义其他属性,也不需要在父对象上使用mappedBy属性,同理父母(User 的物业员工)

    Grails 不需要任何其他东西就可以知道两个类的双向属性以及约束user(unique : true) 也不是。

    所以你的类应该是这样的:

    class User {
    
            static hasOne = [employee: Employee]
    
            static constraints = {
                    employee(nullable: true)
            }
    }
    
    class Employee {
        User supervisor // represents a supervisor
        static belongsTo = [user: User]
    
        static constraints = {
            supervisor(nullable:true)
        }
    }
    

    很高兴知道您的数据库结构如何。但是通过这种方式,所有外键都存储在员工表中。但当然,您可以从这两个实体中导航。如果你有不同的结构,你可以用这个模型映射你当前的数据库。见this

    employee.user
    user.employee
    

    【讨论】:

    • 感谢您的回复!我已经在 Grails 3.2.0 中尝试过您的代码,但它仍然导致 NOT NULL 被添加到员工表的 supervisor_id 列中,尽管有 nullable:true 约束。至于用户对象上的 mappedBy,这是旧代码的遗留物,其中一对一映射是可选的,而拥有方则相反(但外键始终在用户方)跨度>
    • 需要注意的重要一点是,Grails 本身遵守可空约束(即使使用我原来的“坏”代码),因此当您针对现有或手动创建的数据库模式运行时,它会按预期工作。但是,错误地生成了 hbm2ddl 架构,并且将 NOT NULL 应用于这些列,这破坏了我们针对内存中 H2 数据库运行的集成测试。
    • 不客气。我会在几个小时内尝试复制它,并会让你知道。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多