JPA getSingleResult() or null
Solution 1:
Throwing an exception is how getSingleResult()
indicates it can't be found. Personally I can't stand this kind of API. It forces spurious exception handling for no real benefit. You just have to wrap the code in a try-catch block.
Alternatively you can query for a list and see if its empty. That doesn't throw an exception. Actually since you're not doing a primary key lookup technically there could be multiple results (even if one, both or the combination of your foreign keys or constraints makes this impossible in practice) so this is probably the more appropriate solution.
Solution 2:
Try this in Java 8:
Optional first = query.getResultList().stream().findFirst();