This code keeps throwing an error because there aren't any values present in the database:
public Foo getFoo(Parent p1, Parent p2) {
EntityManager entityManager = entityManagerFactory.createEntityManager();
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Foo> criteriaQuery = criteriaBuilder.createQuery(Foo.class);
Root<Foo> root = criteriaQuery.from(Foo.class);
criteriaQuery.select(root).where(criteriaBuilder.and(
criteriaBuilder.equal(root.get("p1"), entityManager.find(Parent.class, p1)),
criteriaBuilder.equal(root.get("p2"), entityManager.find(Parent.class, p2))
));
return entityManager.createQuery(criteriaQuery).getSingleResult();
}
I would prefer if it just returned a null object though. Is there a way that I can do this?
Exception gets thrown on this line:
Foo foo = fooDao.getFoo(p1, p2);
[ObjectDB 2.5.7_03] javax.persistence.NoResultException No matching results for a unique query (error 782) at com.objectdb.jpa.JpaQuery.getSingleResult(JpaQuery.java:754)
You can use
getResultList
instead ofgetSingleResult
.See:
http://www.objectdb.com/java/jpa/query/execute