1

I have the following entities:

  • Area
  • Listing

They are both many-to-many:

  • An area can have many listings
  • A listing can have many areas

Both Area and Listing have other fields like name, domain, etc.

I'm using Spring Web RestController as a way to update the entities.

For example:

@PutMapping("/{id}")
public Area update(@PathVariable Long id, @RequestBody Area update) {
    return areaRepository.save(update);
}

However, as an Area can have many thousands of Listings, it's not practical to pass them all in the update request when I just want to update the Area name and other basic fields in my web application.

For example, the update json in the http request would be:

{
  "id" : 69,
  "name" : "San Francisco",
  "domain" : "foo",
  ...
}

When serialised, the area instance above will have a listings field equal to null (obviously) and then when saved, all association are remove from this Area.

I'm thinking that I could do a select-then-update set of operations and only update the values necessary but that is cumbersome - especially when there are many dozens of non-association fields.

The question would be: how can I try to keep to the above code and http request and not remove all of the existing Listing associations when saving the input area? Is this possible? I want to update the name and other basic fields but not the association fields.

George
  • 11
  • 4

2 Answers2

1

You can use the BeanUtilBean(org.apache.commons.beanutils.BeanUtilsBean).

Step 1: Create custom beanutilbean class.

@Component
public class CustomBeanUtilsBean extends BeanUtilsBean {
    @Override
    public void copyProperty(Object dest, String name, Object value)
            throws IllegalAccessException, InvocationTargetException {
        if(value==null)return;
        super.copyProperty(dest, name, value);
    }
}

Step 2: In your controller while updating. first get the Area from database & use copyProperties method as shown in below.

@PutMapping("/{id}")
public Area update(@PathVariable Long id, @RequestBody Area update) {
    Area areaDB = areaRepository.findOne(update.getId());
    customBeanUtilsBean.copyProperties(areaDB,update);//it will set not null field values of update to areaDB.
    return areaRepository.save(areaDB);
}

Hope this will helps you..:)

Aniket
  • 141
  • 1
  • 5
0

Since you are using spring-data-jpa repository you can write a new method that takes the changed values of Area object with @Modifying and @Query annotations on it.

In the @Query you specify the HQL query with update statement as in here