1

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.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Cyril N.
  • 38,875
  • 36
  • 142
  • 243

1 Answers1

4

Implement the Cloneable interface for the entity, & than calling clone() method will return a shallow copy of the original object. To obtain a deep copy, override it, where you can set id as null & copy non-primitive fields.

@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.   
}

Persisting the cloned object :

MyModel user = MyModel.findById(1);
detachedUser = user.clone(); //-- cloning
user.firstname = "John"; //-- modifying
user.create(); //-- persisting
Nayan Wadekar
  • 11,444
  • 4
  • 50
  • 73