【发布时间】: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