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.
Best regards!
CodePudding user response:
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);
}
CodePudding user response:
- If you don't want to change value of lat and lon then don't set the values using drawing.setLan() and drawing.setLon().
- If you want to change value of lat and lon then use conditions in code for that. if(lon!=null) only then change the value.
i.e.
if(lon!=null){
drawing.setLon(lon);
}
if(lat != null) {
drawing.setLat(lon);
}