I have an insertOrUpdate
method which inserts an Entity
when it doesn't exist or update it if it does. To enable this, I have to findByIdAndForeignKey
, if it returned null
insert if not then update. The problem is how do I check if it exists? So I tried getSingleResult
. But it throws an exception if the
public Profile findByUserNameAndPropertyName(String userName, String propertyName) {
String namedQuery = Profile.class.getSimpleName() + ".findByUserNameAndPropertyName";
Query query = entityManager.createNamedQuery(namedQuery);
query.setParameter("name", userName);
query.setParameter("propName", propertyName);
Object result = query.getSingleResult();
if (result == null) return null;
return (Profile) result;
}
but getSingleResult
throws an Exception
.
Thanks
getSingleResult()
forces you to use exception handling in absence of a value, even though the absence of a value is a common and natural situation. Best practices are that exceptions should only be used for exceptional situations, which the absence of a value is not. A lot of people don't likegetSingleResult()
for this reason. Even the authors of Hibernate, from which JPA was born, criticizegetSingleResult()
. If you also don't like it, please upvote: github.com/eclipse-ee4j/jpa-api/issues/298 – Devabc Nov 29 '20 at 23:47