How to prevent unwanted update of persisted objects?

别来无恙 提交于 2019-12-13 04:58:03

问题


I have a Load class and a Cargo class. An instance of Load contains an instance of Cargo.

class Load {
    Cargo cargo
}

class Cargo {
    String name
    BigDecimal cost
}

Lets say that the name of an instance of Cargo is "rock" and the cost is "11.11". Now I use this instance of Cargo to create an instance of Load. Now that the instance of Load has been created I don't want it's "cargo" to change. For instance, if I change the price of "rock" to "22.22" I don't want the price of the "cargo" in my instance of Load to change. What is the optimal way to handle such a situation?


回答1:


Well, if you can only have one Cargo per Load (as per your example), you'll want to add a cost property to Load. Then you will need to copy over the cost at the time the objects are created. You might be able to do this via an overloaded method in the Load object, or just write your own method to add Cargo to Load.

If you actually need multiple Cargoes per Load, then you'll want an intermediate object to represent the connection. This object will store the price at the time they were associated. That might look like:

class Load {
    LoadCargo loadCargo
}
class LoadCargo {
    Cargo cargo
    BigDecimal cost
}
class Cargo {
    String name
    BigDecimal cost
}

Of course, your object model will be a bit more complicated, because of the indirect relationship to Cargo.

Edit Another way to handle the multiple-related situation is to duplicate the Cargo every time the cost is updated. This might be more efficient if you are expecting cost to be mostly static. I'd handle this by adding a field to "disable" items, like so:

class Cargo {
    String name
    BigDecimal cost
    boolean active = true
}

I believe you can simply clone the Cargo on update like this:

oldCargo = Cargo.get(params.id)
newCargo = new Cargo()
newCargo.properties = oldCargo.properties
// now set the new cost, etc.
newCargo.save()
oldCargo.active = false
oldCargo.save()

That's just a guess, it probably is broken.



来源:https://stackoverflow.com/questions/7279185/how-to-prevent-unwanted-update-of-persisted-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!