No matching results for a unique query (error 782)

303 views Asked by At

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)

2

There are 2 answers

0
ObjectDB On BEST ANSWER

You can use getResultList instead of getSingleResult.

See:

http://www.objectdb.com/java/jpa/query/execute

0
Kayaman On

Catch the exception and return null.