问题描述
|
我有一个带有某些字段的模型,我想在中添加一个新条目
此模型的数据库,但只更改一个字段。在那儿
这样做的最佳方法,而无需创建新实例,并且
每个字段一一设置?
案件 :
public class MyModel extends Model {
public String firstname;
public String lastname;
public String city;
public String country;
public Integer age;
}
我实际拥有的代码
MyModel user1 = MyModel.findById(1);
MyModel user2 = new MyModel();
// is there a way to do it with clone or user1.id = null ? and then create()?
// Actually,I do that :
user2.firstname = \"John\";
user2.lastname = user1.lastname;
user2.city = user1.city;
user2.country = user1.country;
user2.age = user1.age;
user2.create();
我要寻找的东西会做类似的事情:
MyModel user1 = MyModel.findById(1);
MyModel user2 = clone user1;
user2.firstname = \"John\";
user2.create();
要么
MyModel user = MyModel.findById(1);
user.id = null;
user.firstname = \"John\";
user.create();
但是我不知道那样做是否正确。
解决方法
为实体实现
Cloneable
接口,然后调用clone()
方法将返回原始对象的浅表副本。要获取深层副本,请覆盖它,在此处您可以将id设置为null
并复制非原始字段。
@Override
protected Object clone() throws CloneNotSupportedException {
MyModel model = (MyModel) super.clone();
model.setId(null);
//-- Other fields to be altered,copying composite objects if any
return model.
}
保留克隆的对象:
MyModel user = MyModel.findById(1);
detachedUser = user.clone(); //-- cloning
user.firstname = \"John\"; //-- modifying
user.create(); //-- persisting