I love Java8's semantics. I use a lot of such code in my DAOs :
public Optional<User> findBy(String username) {
try {
return Optional.of(
emp.get().createQuery("select u from User u where u.username = :username" , User.class)
.setParameter("username" , username)
.setMaxResults(1)
.getSingleResult()
);
} catch (NoResultException e) {
return Optional.empty();
}
}
It works well , but such code (try catch NoResultException ) scatters over my DAOs. And I have to catch Exception , which somehow lowers performance .
I wonder if it the best solution ? or any better solution , without try-catch ?
If it is not possible (because NoResultException is defined in JPA) , any shortcut to 'templatize' such workflow ?
Thanks.