Java 有没有最好的方法克隆一个模型,只更改一个条目?
我有一个带有一些字段的模型,我想在其中添加一个新条目 此模型的数据库,但仅更改一个字段。有 这样做的最佳方式,无需创建新实例和 每个字段逐个设置 案例:Java 有没有最好的方法克隆一个模型,只更改一个条目?,java,hibernate,jpa,playframework,cloneable,Java,Hibernate,Jpa,Playframework,Cloneable,我有一个带有一些字段的模型,我想在其中添加一个新条目 此模型的数据库,但仅更改一个字段。有 这样做的最佳方式,无需创建新实例和 每个字段逐个设置 案例: public class MyModel extends Model { public String firstname; public String lastname; public String city; public String country; public Integer age; }
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();
或
但是我不知道这样做是否正确。为实体实现
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
为实体实现
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