我不确定哪里出了问题,但似乎我无法从对象实例复制属性并将它们分配给映射,而在保存实例后不更改值。
这是一个示例类:
class Product {
String productName
String proudctDescription
int quantityOnHand
}
提交表单并将其发送到我的控制器后,我可以访问这些值并从productInstance.properties
从实例中可用的地图。我想将属性复制到另一个地图以在编辑期间提交它们之前保留这些值。假设我们正在编辑一条记录,这些是存储在数据库中的值:productName = "My Product"
, productDescription = "My Product Description"
and quantityOnHand = 100
.
我想将它们复制到:
def propertiesBefore = productInstance.properties
这不起作用,因为当我保存 ProductInstance 时,属性 Before 中的值更改为实例所具有的值。
所以我尝试了这个:
productInstance.properties.each { k,v -> propertiesBefore[k] = v }
同样的事情又发生了。我不确定如何按值复制,似乎无论我尝试什么,它都会按引用复制。
EDIT
根据 Pawel P. 的要求,这是我测试的代码:
class Product {
String productName
String productDescription
int quantityOnHand
}
def productInstance = new Product(productName: "Some name", productDescription: "Desciption", quantityOnHand: 10)
def propertiesBefore = [:]
productInstance.properties.each { k,v -> propertiesBefore[k] = (v instanceof Cloneable) ? v.clone() : v }
productInstance.productName = "x"
productInstance.productDescription = "y"
productInstance.quantityOnHand = 9
println propertiesBefore.quantityOnHand // this will print the same as the one after the save()
productInstance.save(flush:true)
println propertiesBefore.quantityOnHand // this will print the same as the one above the save()