1

我有一个带有一些字段的模型,我想在这个模型的数据库中添加一个新条目,但只更改一个字段。有没有最好的方法来做到这一点,而不必创建一个新实例并逐个设置每个字段?

案子 :

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(); 

但我不知道这样做是否正确。

4

1 回答 1

4

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
于 2011-05-30T19:15:52.803 回答