我有一个包含一些字段的模型,我想在其中添加一个新条目 该模型的数据库,但仅更改一个字段。有没有 这样做的最佳方式,无需创建新实例和 每个字段一一设置?
案例:
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
接口(interface),& 而不是调用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
关于java - 是否有一种最好的方法来克隆模型以仅更改一个条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6178137/