JPA Getsingleresult() or Null

JPA getSingleResult() or null

Throwing an exception is how getSingleResult() indicates it can't be found. Personally I can't stand this kind of API. It forces spurious exception handling for no real benefit. You just have to wrap the code in a try-catch block.

Alternatively you can query for a list and see if its empty. That doesn't throw an exception. Actually since you're not doing a primary key lookup technically there could be multiple results (even if one, both or the combination of your foreign keys or constraints makes this impossible in practice) so this is probably the more appropriate solution.

what is better: getSingleResult, or getResultList JPA

getSingleResult throws NonUniqueResultException, if there are multiple rows. It is designed to retrieve single result when there is truly a single result.

The way you did is fine and JPA is designed to handle this properly. At the same time, you cannot compare it against getSingleResult any way, since it won't work.

However, depend on the code you are working on, it is always better to refine the query to return single result, if that's all what you want - then you can just call getSingleResult.

getSingleResult() in JPA thorws exceptions

JPA getSingleResult() or null

http://sysout.be/2011/03/09/why-you-should-never-use-getsingleresult-in-jpa/

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

Jpa getSingleResult() behoviour if no entity is there sometimes it's shows exception and sometime it's shows error

There's a difference between the lack of results (no rows) and NULL. What you're getting is a single NULL result, so no exception should be thrown.

Aggregate functions return NULL if there are no rows for which to calculate the aggregate, which makes this a bit convoluted. The query itself (FROM IptReceiveOrder...) returns 0 rows, but the MAX(model.id) changes that into a single NULL row.

Best way to handle when you are expecting 0 or 1 results from JPA query

You can find a discussion about this topic here:
JPA getSingleResult() or null

Looks like there are no better alternatives.



Related Topics



Leave a reply



Submit