如何在Grails / GORM中将Domain Class模型对象从一个派生类更改为另一个派生类 [英] How to change a Domain Class model object from one derived class to another in Grails/GORM

查看:246
本文介绍了如何在Grails / GORM中将Domain Class模型对象从一个派生类更改为另一个派生类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下Grails GORM Domain Classes并使用每个层次继承:

  class Book {
static belongsTo = [parent:Parent]
字符串标题
}

抽象类父类{
static hasMany = [books:Book]
}

class A extends Parent {
String asset
}

class B extends Parent {
String asset
}

假设我从数据库中检索了A类的一个实例。我想将它转换为B类的一个实例。什么是grails惯用的方式来做到这一点?



没有hasMany关系,我只需删除A并创建一个新的B.但我不想要通过大量的书籍和更新他们的parent_id字段指向新的B的开销。



在引擎盖下,我基本上只想执行SQL UPDATE将数据库字段parent.class从A更改为B.那么在GORM / Grails中执行此操作的建议方式是什么?

解决方案

看起来像是设计缺陷的标志。

你可以试着用继承来代替继承 - 优先于类继承的对象组合。 (Gang of Four 1995:20) - 从 Parent 提取a,比如 HasAsset 接口,以及添加对 HasAsset 的引用。



Groovy代表团可以提供帮助。


Given the following Grails GORM Domain Classes and using table-per-hierarchy inheritance:

class Book {
  static belongsTo = [ parent: Parent ]
  String title
}

abstract class Parent {
  static hasMany = [ books: Book ]
}

class A extends Parent {
  String asset
}

class B extends Parent {
  String asset
}

Say I have retrieved an instance of class A from the database. I want to convert it to an instance of class B. What is the grails idiomatic way to do this?

Without the hasMany relation, I would just delete A and create a new B. But I don't want the overhead of going through a large number of Books and updating their parent_id fields to point to the new B.

Under the hood, I essentially just want to perform an SQL UPDATE to change the database field parent.class from A to B. So what's the recommended way to do this in GORM/Grails?

解决方案

Looks like a sign of design flaw.

You could try to replace inheritance with aggregation - "Favor object composition over class inheritance." (Gang of Four 1995:20)" - extract a, say, HasAsset interface from Parent and add a reference to HasAsset.

Groovy delegation could help.

这篇关于如何在Grails / GORM中将Domain Class模型对象从一个派生类更改为另一个派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆