JPA getSingleResult() or null
Posted
by Eugene Ramirez
on Stack Overflow
See other posts from Stack Overflow
or by Eugene Ramirez
Published on 2010-01-04T23:15:24Z
Indexed on
2010/05/21
19:50 UTC
Read the original article
Hit count: 328
Hi. 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
© Stack Overflow or respective owner