How to Update Only the Incoming Fields in a Model Using Spring Data Jpa

How to update only the incoming fields in a model using spring data jpa?

I found that the exact requirement of my question can't be fulfilled. Dozer Bean Mapper seemed like an option but it's more about mapping bean objects of different classes where we can correspond the fields to be mapped which is not my case.

The solution was to alter the approach wherein all the required information are sent while doing an update.

As Simon pointed out in the comment:

Simple answer: that's not possible. Because after deserialization if
fields are missing the value is null. Java is a static typed language
and does not fit very well with your requirments.

Update only selected Fields using entityManager

If you are executing the update using native query, you need not merge the entity. The following code should fix this.

    @Override
@Transactional
public void updateStocksPrices(Stocks stocks) {
Query query = entityManager.createNativeQuery("UPDATE stocks set price=:price WHERE id=:id");
query.setParameter("price", stocks.getPrice());
query.setParameter("id" stocks.getId());
query.executeUpdate();
}

Spring Partial Update Object Data Binding

I've just run into this same problem. My current solution looks like this. I haven't done much testing yet, but upon initial inspection it looks to be working fairly well.

@Autowired ObjectMapper objectMapper;
@Autowired UserRepository userRepository;

@RequestMapping(value = "/{id}", method = RequestMethod.POST )
public @ResponseBody ResponseEntity<User> update(@PathVariable Long id, HttpServletRequest request) throws IOException
{
User user = userRepository.findOne(id);
User updatedUser = objectMapper.readerForUpdating(user).readValue(request.getReader());
userRepository.saveAndFlush(updatedUser);
return new ResponseEntity<>(updatedUser, HttpStatus.ACCEPTED);
}

The ObjectMapper is a bean of type org.codehaus.jackson.map.ObjectMapper.

Hope this helps someone,

Edit:

Have run into issues with child objects. If a child object receives a property to partially update it will create a fresh object, update that property, and set it. This erases all the other properties on that object. I'll update if I come across a clean solution.



Related Topics



Leave a reply



Submit