Search code examples
javasqlhibernatejpa

JPA - getSingleResult vs LIMIT 1


What is the difference between .getSingleResult() and LIMIT 1 for example in the below hibernate 6 query:

@Override
public Test customQuery3(Long id) {
return (Test) entityManager.createQuery(
                "SELECT NEW com.view.Test(a.id, b) FROM Author a " +
                        "LEFT JOIN Book b ON b.author.id=a.id " +
                        "WHERE b.id=:id " +
                        "GROUP BY a, b ORDER BY b.newestBook DESC LIMIT 1")
        .setParameter("id", id)
        .getSingleResult();

}

From reading SQL documentation LIMIT 1 restricts the results to one and in the example above the newest.

The documentation on .getSingleResult() appears to do the same albeit with some errors thrown if the id is not found.

So why are both needed?


Solution

  • The doc says if the query returned more than one row, it throws NonUniqueResultException. Besides, when using getResultList(), it returns a List rather than an Object. When you know it SHOULD return one row, better to use getSingleResult(), because returning more rows in this case is a logic error or the data is in an inconsistent state, better to stop processing.