有没有最好的方法来克隆模型以仅更改一个条目?
我有一个包含一些字段的模型,我想在其中添加一个新条目 该模型的数据库,但仅更改一个字段。有没有 这样做的最佳方法,无需创建新实例 每个字段一一设置?
案例:
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();
但我不知道这样做是否正确。
I have a model with some fields, and I'd like to add a new entry in
the database of this model, but with changing only one field. Is there
a best way to do so, without having to create a new instance and
setting one by one each field ?
Case :
public class MyModel extends Model {
public String firstname;
public String lastname;
public String city;
public String country;
public Integer age;
}
And the code I actually have
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();
What I am lookig for would to do something like :
MyModel user1 = MyModel.findById(1);
MyModel user2 = clone user1;
user2.firstname = "John";
user2.create();
or
MyModel user = MyModel.findById(1);
user.id = null;
user.firstname = "John";
user.create();
But I don't know if it's correct to do it like that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为实体实现
Cloneable
接口,&调用clone()
方法将返回原始对象的浅表副本。要获取深拷贝,请重写它,您可以将 id 设置为null
&复制非原始字段。保留克隆的对象:
Implement the
Cloneable
interface for the entity, & than callingclone()
method will return a shallow copy of the original object. To obtain a deep copy, override it, where you can set id asnull
& copy non-primitive fields.Persisting the cloned object :