Home > Software engineering >  How to Update the Entity Efficeintly
How to Update the Entity Efficeintly

Time:09-30

I have model class:

@Entity 
public class Customer {
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long id;
    public String name;
    public String phone;
    //...
}

Now there is an update operation in which I want to update the existing data. My code:

public void updateCustomer(Customer customer) {
    Customer existingCustomer = customerRepository.findById(customer.getId())
                                                  .orElse(null);

    /* Now here I want to update only fields which are not null            
       if(customer.getInfo() != null)
       existingCustomer.setInfo(customer.getInfo()); 
    */
    customerRepository.save(existingCustomer);
}

How to do this in an effective way as I can't check for each field and set it in my object.

CodePudding user response:

One possible solution would be to combine JsonNullable and MapStruct features as described in this very detailed article.

CodePudding user response:

I'm assuming that your fields are public as a shortcut for making the question straightforward.

I suggest you to create a special method in your entity that accepts a second entity and iterates over their fields.

e.g.


    class Customer {
        // one hundred fields here
        public void updateOnlyNonNulls(Customer customer){
            for (Field declaredField : Customer.class.getDeclaredFields()) {
                try {
                    Object o = declaredField.get(customer);
                    if(o!=null)
                        declaredField.set(this, o);
                } catch (IllegalAccessException e) {
                    throw new AssertionError("Should not happen");
                }
            }
        }
    }

Do not be reluctant to add rich behavior to your entities.

  • Related