JPA Query – getSingleResult() – Not a good API
JPA Query API has two methods to retrieve results from an select query.
1. getSingleResult() – Execute a SELECT query that returns a single untyped result.
2. getResultList() – Execute a SELECT query and return the query results as an untyped List.
The weird part of the getSingleResult() method is that it throws a NoResultException – if there is no result found. NoResultException is a runtime exception.
According to the EffectiveJava “Use checked exceptions for conditions from wich the caller can reasonably be expected to recover. Use runtime exceptions to indicate programming errors”. Getting no result from an select query is not a programming error.
The workaround to overcome this api is to use getResultList() method and check if the list is empty. getSingleResult() can only be used in situations where “I am totally sure that this record exists. Shoot me if it doesn’t“
Posted on April 15, 2011, in hibernate, jpa and tagged hibernate, jpa. Bookmark the permalink. Leave a comment.
Leave a comment
Comments 0