1

How do I modify only part of an entity in Spring Data JPA?

Here is my code.

public void modifyDrawing(Long no, String name, Double lat, Double lon, String physicalName, String desc) {
   Drawing drawing = drawingRepository.findById(no)
       .orElseThrow(NoSuchElementException::new);

   drawing.setName(name);
   drawing.setLat(lat);
   drawing.setLon(lon);
   drawing.setPhysicalName(physicalName);
   drawing.setDesc(desc);
   drawingRepository.save(drawing);
}

At this time, if lat and lon are null, I want to keep the values without changing them. I am wondering how to update the entity value using only non-null parameter values.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [JPA: update only specific fields](https://stackoverflow.com/questions/27818334/jpa-update-only-specific-fields) – İsmail Y. Apr 12 '22 at 09:57

1 Answers1

2

You should add an if check to make sure the latitude/longitude are not null before calling their setters.

public void modifyDrawing(Long no, String name, Double lat, Double lon, String physicalName, String desc) {
    Drawing drawing = drawingRepository.findById(no)
        .orElseThrow(NoSuchElementException::new);

    drawing.setName(name);
    if (lat != null) {
        drawing.setLat(lat);
    }
    if (lon != null) {
        drawing.setLon(lon);
    }
    drawing.setPhysicalName(physicalName);
    drawing.setDesc(desc);
    drawingRepository.save(drawing);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360