Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: update only specific fields

Is there a way for updating only some fields of an entity object using the method save from Spring Data JPA?

For example I have a JPA entity like this:

@Entity public class User {    @Id   private Long id;    @NotNull   private String login;    @Id   private String name;    // getter / setter   // ... } 

With its CRUD repo:

public interface UserRepository extends CrudRepository<User, Long> { } 

In Spring MVC I have a controller that get an User object for update it:

@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> updateUser(@RequestBody User user) {     // Assuming that user have its id and it is already stored in the database,    // and user.login is null since I don't want to change it,    // while user.name have the new value     // I would update only its name while the login value should keep the value     // in the database    userRepository.save(user);     // ... } 

I know that I could load the user using findOne, then change its name and update it using save... But if I have 100 fields and I want to update 50 of them it could be very annoying change each value..

Is there no way to tell something like "skip all null values when save the object"?

like image 290
Andrea Avatar asked Jan 07 '15 11:01

Andrea


2 Answers

Using JPA you can do it this way.

CriteriaBuilder builder = session.getCriteriaBuilder(); CriteriaUpdate<User> criteria = builder.createCriteriaUpdate(User.class); Root<User> root = criteria.from(User.class); criteria.set(root.get("lastSeen"), date); criteria.where(builder.equal(root.get("id"), user.getId())); session.createQuery(criteria).executeUpdate(); 
like image 29
Arjun Nayak Avatar answered Sep 17 '22 11:09

Arjun Nayak


I had the same question and as M. Deinum points out, the answer is no, you can't use save. The main problem being that Spring Data wouldn't know what to do with nulls. Is the null value not set or is it set because it needs to be deleted?

Now judging from you question, I assume you also had the same thought that I had, which was that save would allow me to avoid manually setting all the changed values.

So is it possible to avoid all the manuel mapping then? Well, if you choose to adhere to the convention that nulls always means 'not set' and you have the original model id, then yes. You can avoid any mapping yourself by using Springs BeanUtils.

You could do the following:

  1. Read the existing object
  2. Use BeanUtils to copy values
  3. Save the object

Now, Spring's BeanUtils actual doesn't support not copying null values, so it will overwrite any values not set with null on the exiting model object. Luckily, there is a solution here:

How to ignore null values using springframework BeanUtils copyProperties?

So putting it all together you would end up with something like this

@RequestMapping(value = "/rest/user", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public ResponseEntity<?> updateUser(@RequestBody User user) {     User existing = userRepository.read(user.getId());    copyNonNullProperties(user, existing);    userRepository.save(existing);     // ... }  public static void copyNonNullProperties(Object src, Object target) {     BeanUtils.copyProperties(src, target, getNullPropertyNames(src)); }  public static String[] getNullPropertyNames (Object source) {     final BeanWrapper src = new BeanWrapperImpl(source);     java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();      Set<String> emptyNames = new HashSet<String>();     for(java.beans.PropertyDescriptor pd : pds) {         Object srcValue = src.getPropertyValue(pd.getName());         if (srcValue == null) emptyNames.add(pd.getName());     }     String[] result = new String[emptyNames.size()];     return emptyNames.toArray(result); } 
like image 137
William Avatar answered Sep 17 '22 11:09

William