【发布时间】:2021-10-19 01:04:25
【问题描述】:
我有 2 个实体 EntityOne 和 EntityTwo 映射到数据库中的 2 个表。
EntityTwo 中的所有列也存在于EntityOne 中,因为EntityTwo 是一个子系统的读取表。
现在,下面是一些解释场景的代码, 我正在使用 spring data repo 和 java Optional,带有 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 是 EntityOne 类中的一个方法,它创建一个新的 EntityTwoPrimaryKey 对象并填充所有值。
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());
}
现在,如果您在所有上述 3 种方法中都看到了可选检查,以确保只有在我们拥有所有数据时才会执行操作。 我想在一个可选管道中编写所有代码。
如果我像下面这样写,则没有编译错误。但是当repoOne.findById在数据库中找不到任何数据时会发生什么?
我只在repoTwo::findById 之后检查ifPresent()
repoOne.findById(entityOne.getEntityOnePrimaryKey())
.map(entityOne::createEntityTwoPrimaryKey)
.flatMap(repoTwo::findById) //returns Optional<EntityTwo>
.ifPresent(repoTwo::delete);
【问题讨论】: