【发布时间】:2017-01-02 14:26:29
【问题描述】:
我很困惑如何实现这一点,或者它是否真的可能/合适。我和我的同事正在使用 Grails 3 为客户端构建一个 Web 应用程序。他创建了初始域,我猜想这是来自移动应用程序的 Realm 模型的几乎一对一的副本。从那以后,我对它们进行了修改,试图让某种形式的深度克隆能够发挥作用,因为三个域具有一对多的关系。
问题
我将如何创建域的深层副本?我尝试了建议的答案,但收效甚微:
从不同的地方挑选想法我来制定如下所示的clone(Domain) 方法。它几乎可以工作(我认为),但在集合抛出 HibernateException - Found shared references to a collection: Location.equipments 时存在问题。
在控制器中调用为:
def copy() {
Survey.clone(Survey.get(params.id))
redirect action: 'index'
}
有什么想法或指导吗?
目前的域名如下:
class Survey {
int id
String name
String contactName
String contactEmail
String facilityAddress
String facilityCity
String facilityStateProvince
String facilityZip
String distributorName
String distributorEmail
String distributorPhoneNumber
static Survey clone(Survey self) {
Survey clone = new Survey()
String exclude = "locations"
clone.properties = self.properties.findAll {
it.key != exclude
}
self.locations.each {
Location copy = Location.clone it
clone.addToLocations copy
}
clone.save()
}
static transients = ['clone']
static belongsTo = User
static hasMany = [locations: Location]
}
class Location {
int id
String name
String[] hazardsPresent
HazardType[] hazardTypes
ExposureArea[] exposureArea
RiskLevel exposureLevel
String comments
byte[] picture
static Location clone(Location self) {
Location clone = new Location()
String[] excludes = ['equipment', 'products']
clone.properties = self.properties.findAll {
!(it.key in excludes)
}
self.equipments.each {
Equipment copy = Equipment.clone it
self.addToEquipments copy
}
self.products.each {
RecommendedProduct copy = new RecommendedProduct()
copy.properties = it.properties
copy.save()
clone.addToProducts copy
}
clone.save()
}
static transients = ['clone']
static belongsTo = Survey
static hasMany = [equipments: Equipment, products: RecommendedProduct]
static constraints = {
picture(maxSize: 1024 * 1024)
}
}
class Equipment {
int id
EquipmentType type
String name
Brand brand
// Redacted 26 boolean properties
// ...
static Equipment clone(Equipment self) {
Equipment clone = new Equipment()
String exclude = "extras"
clone.properties = self.properties.findAll {
it.key != exclude
}
self.extras.each {
EquipmentQuestionExtra copy = new EquipmentQuestionExtra()
copy.properties = it.properties
copy.save()
clone.addToExtras copy
}
clone.save()
}
static transients = ['clone']
static belongsTo = Location
static hasMany = [extras: EquipmentQuestionExtra]
}
class RecommendedProduct {
int productId
int quantityChosen
String comment
static belongsTo = Location
}
class EquipmentQuestionExtra {
int id
String questionText
String comment
byte[] picture
static belongsTo = Equipment
static constraints = {
picture(maxSize: 1024 * 1024)
}
}
【问题讨论】:
-
您正在进行的克隆应该是克隆每个对象,而不管其类型如何。因此,也要克隆集合。
标签: grails grails-orm