Reputation: 1688
I use this code to make SQL request to find DB record:
public Optional<Subscription> findSubscriptionsByUserEmail(String email) {
String hql = "SELECT s " +
"FROM " + Subscription.class.getName() + " s " +
"INNER JOIN " + Orders.class.getName() + " o ON s.orderId = o.id " +
"INNER JOIN " + Users.class.getName() + " u ON u.id = o.userId " +
"WHERE u.email = :email " +
"ORDER BY s.createdAt DESC ";
TypedQuery<Subscription> query = entityManager.createQuery(hql, Subscription.class).setMaxResults(1).setParameter("email", email);
Optional<Subscription> subscription = Optional.of(query.getSingleResult());
return subscription;
}
But when I don't have a record I get exception: No entity found for query
Do you know how I can skip this exception and continue code execution?
Upvotes: 0
Views: 67
Reputation: 2303
The simplest way to do it is either to try/catch
the optional object to see there has been a data sent back or make simple check to see if the optional has an object in it.
Eg:
!subscription.isPresent()? null:subscription;
Upvotes: 1