Core Java

Handling JPA NoResultException When No Entity Is Found

In JPA or Hibernate, the runtime error javax.persistence.NoResultException: No entity found for query occurs when Query.getSingleResult() or TypedQuery.getSingleResult() expects exactly one result, but the query returns none, causing JPA to throw an exception instead of returning null, which can lead to unexpected failures if not handled properly. In this article, we’ll explore why it happens and show reliable ways to avoid or manage this exception in your applications.

1. Why NoResultException Happens

According to the JPA specification, getSingleResult() is required to throw a NoResultException when a query returns zero results and a NonUniqueResultException when more than one result is found, ensuring that the method only succeeds when exactly one matching record exists.

Example of Problematic Usage

    public Product findProductBySku(String sku) {
        TypedQuery<Product> query = em.createQuery("SELECT p FROM Product p WHERE p.sku = :sku", Product.class);
        query.setParameter("sku", sku);

        return query.getSingleResult(); // Throws NoResultException if not found
    }

Because this call expects exactly one result, it throws an exception instead of returning null when nothing is found.

2. How to Fix or Handle NoResultException

When a query may return zero results, you should never rely on getSingleResult() without protection. Instead, JPA and Spring Data offer several safer alternatives that allow your application to handle missing records gracefully. The following approaches show how to avoid unwanted runtime errors.

2.1 Use getResultList() Instead

Because getResultList() never throws a NoResultException, it is a safe general-purpose way to query when results are not guaranteed.

    public Product findProductBySku(String sku) {
        TypedQuery<Product> query = em.createQuery("SELECT p FROM Product p WHERE p.sku = :sku", Product.class);
        query.setParameter("sku", sku);

        return query.getResultList()
                .stream()
                .findFirst()
                .orElse(null);
    }

This solution converts the query result into a list and extracts the first match if present. When there are no rows, it simply returns null, allowing the application to continue without crashing. This makes it ideal when a result may or may not exist, while still keeping the code clean and predictable.

2.2 Catch the Exception

If you need to use getSingleResult(), wrapping it in a try/catch allows you to gracefully handle missing records, and you can create custom exceptions to provide more meaningful error information than the generic NoResultException.

    public Product findProductBySku(String sku) {
        try {
            return em.createQuery(
                    "SELECT p FROM Product p WHERE p.sku = :sku", Product.class)
                    .setParameter("sku", sku)
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

This approach relies on getSingleResult(), but prevents failures by catching the NoResultException. Although it works, it is generally less efficient because using exceptions for control flow can reduce performance and readability.

2.3 Spring Data JPA with Optional

Spring Data JPA provides a clean API that avoids exceptions entirely by returning an Optional.

public interface ProductRepository extends JpaRepository<Product, Long> {

    Optional<Product> findBySku(String sku);
}

By returning Optional<Product>, this method enforces explicit handling of missing data at the call site. It encourages cleaner code practices, reduces the chance of NullPointerExceptions, and avoids exception-driven logic.

Usage Example

@Service
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public Optional<Product> findOptionalProduct(String sku) {
        return productRepository.findBySku(sku);
    }
}

3. Conclusion

In this article, we explored the causes of the JPA NoResultException: No entity found for query and demonstrated multiple ways to handle it safely. We covered approaches using getResultList(), exception handling and Spring Data JPA Optional. By applying these strategies, we can write more predictable JPA code, avoid runtime failures, and ensure that queries returning no results are handled gracefully.

4. Download the Source Code

This article explored Java Persistence API (JPA) handling of NoResultException when no entity is found during query execution.

Download
You can download the full source code of this example here: java jpa noresultexception no entity found for query

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button