In Spring JPA, I have two repositories like so,
public interface RepoA extends .... {
Optional<A> findByDomain(String domain);
}
public interface RepoB extends .... {
Optional<B> findByHost(String host);
}
And in my service implementation I would like to first check if theres anything returned by RepoA
. If there is then convert to a DTO. Otherwise I would like to check if there is anything returned by RepoB
and again convert it to a DTO. If nothing is being returned by either repositories then return essentially a null
. So using Optional
I implemented the service like below,
public class ServiceImpl ... {
private RepoA repoA;
private RepoB repoB;
private Mapper mapper;
private BDTO findByHost(String domain) {
return Optional.ofNullable(domain)
.flatMap(repoB::findByHost)
.map(t -> mapper.B_To_BDTO(t))
.orElse(null);
}
public Optional<BDTO> findByDomainOrHost(String domain) {
return Optional.of(Optional.ofNullable(domain)
.flatMap(repoA::findByDomain)
.map(i -> mapper.B_To_BDTO(i.getTransport()))
.orElseGet(() -> findByHost(domain)));
}
}
So what I'm trying to do is return a Optional<BDTO>
which could either be a mapped result of either repoA::findByDomain
or repoB::findByHost
. Is there another "nicer" way to achieve this using Optional
?