Grails GORM一对一关系,同时保留现有条目

Grails GORM一对一关系,同时保留现有条目,grails,gorm,Grails,Gorm,在阅读了GORM的文档之后,我找到了如何在对象之间创建一对一关系的方法。然而,我还没有弄明白如何去实现我想要的关系。我试图创建的关系是一对一的关系,但出于历史目的保留了以前的行条目 例如,一辆汽车可以在其整个生命周期内拥有多个车主。如果我有Car和Owner域对象,如何在Owners表中为给定的Car ID指定最新的条目是正确的?有很多不同的方法来建模。在国际海事组织,最灵活的方法之一是: class User { String name static hasMany = [owners

在阅读了GORM的文档之后,我找到了如何在对象之间创建一对一关系的方法。然而,我还没有弄明白如何去实现我想要的关系。我试图创建的关系是一对一的关系,但出于历史目的保留了以前的行条目


例如,一辆汽车可以在其整个生命周期内拥有多个车主。如果我有Car和Owner域对象,如何在Owners表中为给定的Car ID指定最新的条目是正确的?

有很多不同的方法来建模。在国际海事组织,最灵活的方法之一是:

class User {
  String name
  static hasMany = [ownerships: Ownership]
}

class Car {
  String name
  static hasMany = [ownerships: Ownership]
}

class Ownership {
  Date start
  Date end
  static belongsTo = [owner: User, car: Car]
}
例如,当Ann将汽车出售给Bob时,我们将Ann的
所有权
记录的结束时间设置为出售时间,并为Bob保存一条新的
所有权
记录,开始时间设置为出售时间

如果获取汽车的当前车主是我们经常需要执行的操作,那么我们可以在
car
中添加
currentOwner
方法

class Car {
  String name
  static hasMany = [ownerships: Ownership]

  Ownership currentOwner() {
    // depending on how this method is used, you might want to
    // return the User instead of the Ownership
    Ownership.findByEndIsNullAndCar(this)
  } 
}