I have 2 Entity EntityOne and EntityTwo mapped to 2 tables in DB.
All columns in EntityTwo are present in EntityOne too, as EntityTwo is the read table for one sub-system.
Now, below is some code to explain a scenario, I'm using spring data repo and java Optional, with java-8
void doMagic(EntityOne entitytOne){
//Only if EntityOne present in Database, go delete entity Two.
repoOne
.findById(entitytOne.getPrimaryKey()); //returns Optional<EntityOne>
.ifPresent(this::deleteAssociatedEntityTwo);
}
void deleteAssociatedEntityTwo(EntityOne entityOne){
// Only If able to find an EntityTwo associated with EntityOne in Database, then delete it
fetchEntityTwo(entityOne) //returns Optional<EntityTwo>
.ifPresent(repoTwo::delete);
}
Absent EntityOne::createEntityTwoPrimaryKey is a method in EntityOne class which create a new EntityTwoPrimaryKey object and populate all values.
private Optional<EntityTwo> fetchEntityTwo(EntityOne entityOne) {
// Only if passed entityOne is not null, query the Db and return Optional<EntityTwo>
return Optional
.ofNullable(entityOne)
.map(EntityOne::createEntityTwoPrimaryKey)
.map(repoTwo::findById) //returns Optional<EntityTwo>
.orElse(Optional.empty());
}
Now if you see in all above 3 methods have are optional checks to make sure action happen only if we have all data. I want to write this all code in one optional pipeline.
If I write like below, There are no compilation errors. But what will happen when repoOne.findById cant find any data in database ?
I'm only checking ifPresent() after repoTwo::findById
repoOne.findById(entityOne.getEntityOnePrimaryKey())
.map(entityOne::createEntityTwoPrimaryKey)
.flatMap(repoTwo::findById) //returns Optional<EntityTwo>
.ifPresent(repoTwo::delete);