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