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.
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);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.