【问题标题】:grails GORM: how to access id of super classgrails GORM:如何访问超类的ID
【发布时间】:2013-05-27 13:31:18
【问题描述】:

我继承了一个需要维护的 Grails 1.3.9 项目。

有一种情况需要扩展其中一个控制器以记录扩展约会的创建。

约会是这样定义的:

class Appointment implements Serializable{

    static mapping = {
        table 'appointment'
        version false
        tablePerHierarchy false
        id generator:'sequence', params:[sequence:'seq_te_id']
        cache true
        columns{
            id column:'te_id'
            start column: 'te_start'
            // Other columns follow
        }
     }
  }

特别约会:

class SpecialAppointment extends Appointment implements Serializable {

  static mapping = {
      table 'special_appointment'
      cache true
      columns{
          id column: 'pt_id'
          comment column: 'pt_name'
          // other columns
      }
   }
}

历史记录:

class AppointmentHistory {
    static mapping = {
        version false
        table 'appointment_history'
        id generator: 'sequence', params:[sequence:'seq_th_id']
        cache true
        columns {
            id column: 'th_id'
            termin column: 'pt_id'
            // other columns
        }
    }
}

在创建以 Appointment 作为其基类的 SpecialAppointment 的控制器中,我需要创建并保存与 Appointment 有关系的 AppointmentHistory 的新实例。

def app = new SpecialAppointment()
// set fields here

app.save(flush:true)

// save history log
def history = new AppointmentHistory(appointment: app)

我在创建历史对象时传递了 SpecialAppointment 的实例,但它是错误的,因为它使用了它的 ID,而不是 Appointment 的 ID。

不幸的是,我无法找出正确的语法从刚刚保存的派生类实例中访问超类的成员。

请指教。

【问题讨论】:

  • 在我看来这应该是一个组合而不是一个扩展 - SpecialAppointment 应该是 Appointment 的子类,而应该是一个单独的类,它包含 (可能不可为空)对约会的引用。
  • 是的,以这种方式实现它可能会更好,但是这是更大应用程序的一部分,我宁愿不改变这些关系。显式访问超类成员的正确语法是什么?

标签: grails orm grails-orm grails-domain-class


【解决方案1】:

SpecialAppointment 是 Appointment 的子类,在表中只生成一个对象和一行,因此它们具有共同的 ID。继承不是一个子对象包含超对象的关系,而是一个子对象也是超对象的关系

也就是说,使用SpecialAppointment的ID就可以了,因为SpecialAppointment也可以被Appointment类对象引用

【讨论】:

  • 我认为 SpecialAppointment 应该引用一个 Appointment。就像答案中所说的那样,您没有约会和特别约会,只有第二个。如果您想从 SpecialAppointment 访问相关约会,则必须存储和引用这两个项目
  • 约会没有自己的ID,他们有一个共同的ID,因为他们是一个对象(不是两个)
  • @KamilMikolajczyk 每个域类都映射到自己的表。创建新的 SpecialAppointment 时,也会创建 Appointment 的相关条目。两者都有 id 列。 (grails.org/doc/latest/guide/GORM.html#inheritanceInGORM)
  • 哦,好吧,我没有看到“tablePerHierarchy”映射,但我仍然希望它们在两个表中具有相同的 ID
  • @KamilMikolajczyk 他们没有相同的 ID,因为 SpecialAppointment 不是唯一从 Appointment 继承的类。
【解决方案2】:

真正的问题是域类之间的关系没有正确设置。

AppointmentHistory 需要 belongsTo AppointmentAppointment 需要 hasMany AppointmentHistory。必须将历史记录项添加到与app.addHistoryItem(history) 的约会中。

这些更改解决了问题。

感谢大家的支持。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2012-05-13
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 2010-12-22
    相关资源
    最近更新 更多