I need to get car info from a 3rd party web service and persist the data in my application DB. If my DB already has the car, I only update property values that may have changed. Otherwise, I create and save the car:
@Transactional //Spring Transaction
void saveCars() {
//get CarInfo from a webservice
List<CarInfo> carInfos = getCarInfo();
// now get each Car from my application DB
// that correspond to each CarInfo.
Set<Car> cars = mySpringCarRepo.findByCarInfoIdIn(
carInfos.stream().map(c -> c.getId())
.collect(Collectors.toSet());
for (CarInfo carInfo : carInfos) {
// If a car for the carInfo
// is already in my application
// just update it if some carInfo has changed.
// If a car is not there, create and save it to DB.
Car car = cars
.stream()
.filter(c -> c.getCarInfoId().equals(carInfo.getId())
.findAny()
.map(c -> updateCar(carInfo, car))
.orElseGet(() -> createCar(carInfo);
mySpringCarRepo.save(car);
}
}
I have the following questions / concerns about this code:
- Is this an inappropriate use of
Optional
'smap
method? I'm not mapping to a new object but rather just returning the same car with some properties potentially updated. - The save method is really only required to be called for cars created in the
orElseGet
. Due to being in a transaction, the updates to the car will be persisted without the save call. It seems redundant and perhaps confusing to call save.
Effective Java 3rd edition states that many uses of isPresent
can profitably be replaced by other Optional
methods. So that has led me to the path of using map
& orElseGet
and the fact that Java 8 does not have a ifPresentOrElse
method on Optional
.