Why you should never use getSingleResult() in JPA

As long as I’m using JPA I notice that the use of getSingleResult and getResultList is often confused. In the javadoc there is no clear specification of what to use.
getResultList()

Execute a SELECT query and return the query results as an untyped List.

getSingleResult()

Execute a SELECT query that returns a single untyped result.

So this doesn’t get us much further. So lets explore the problem. Both methods are used to retrieve Entities from our database. We use the getResultList() if there is no guarantee how many results we want to retrieve, the getSingleResult is used to retrieve exactly one row.
So the only doubt for what method to use, is when we retrieve 1 row from our database. A perfect example for this use-case is a findById query, where we retrieve an Entity based upon its ID.
There are 3 ways to do this. The most appropriate way is to use the EntityManger.find() method. This method returns a typed instance of the entity when it is found, null when it is not found.
The other 2 ways is by a NamedQuery. Why would we want to use a NamedQuery when we have the find method? Sometimes we need to retrieve a lazy collection, by adding afetch join. An other example is when we have a composite key, we can still use the EntityManager.find() method, but I often see the use of a named query in this case. (don’t do this, bad programming)
So we created our named query

1
2
final Query query = getEntityManager().createNamedQuery("Entity.findById");
query.setParameter("id", id);

The most natural reaction is to call the getSingleResult() method on the query. This returns only one row and the result of a ‘findById’ query should only be one row. But what if the row isn’t in the database (anymore)? We get an unchecked exception: NoResultException. Is this what we expect?
If you look in Effective Java by Joshua Bloch, we read: ‘Use checked exceptions for conditions from wich the caller can reasonably be expected to recover. Use runtime exceptions to indicate programming errors’.
So what does this tell us? When a getSingleResult Query returns no rows, we get an unchecked exception, thus a programmer error, there is no way to recover from this. This is not correct. We never know for sure what we can expect from our database, so throwing an unchecked exception seems the wrong choice for this use-case.
The only use for getSingleResult() is when we are executing a scalar (count, sum, avg) query. This is a query wich will alway return a row, otherwise we are in an exceptional case, so the exception is allowed.
So, how do we solve our example with our named query? Simple

1
2
3
4
5
6
List results = query.getResultList();
Entity foundEntity = null;
if(!results.isEmpty()){
    // ignores multiple results
    foundEntity = results.get(0);
}

Spring Tutorials

pring Integration 2
Spring Integration 2: Integrating RabbitMQ and Web Service
Spring Integration 2: Integrating a JDBC and WS System

Spring REST
Spring 3: REST Web Service Provider and Client Tutorial (Part 1)
Spring 3: REST Web Service Provider and Client Tutorial (Part 2)

Spring Data and MongoDB
Spring Data – MongoDB (Revision for 1.0.0.M2)
Spring Data – MongoDB Tutorial (1.0.0.M1)

Spring MVC 3 and Apache POI
Spring 3 – Apache POI – Hibernate: Creating an Excel Report Tutorial

Spring MVC 3 and jQuery
Spring MVC 3 and jQuery Integration Tutorial

Spring MVC 3 and DWR
Spring MVC 3 and DWR 3 Integration Tutorial

Spring MVC 3 and MongoDB
Spring MVC 3: Using a Document-Oriented Database – MongoDB

Spring Scheduling
Spring 3 – Quartz Scheduling
Spring 3 – Task Scheduling via Annotations: @Scheduled, @Async
Spring 3 – Task Scheduling via “scheduled-tasks” Element

Spring LDAP
Spring Security – MVC: Using an Embedded LDAP Server
Spring Security – MVC: Using an LDAP Authentication Provider
LDAP – Apache Directory Studio: A Basic Tutorial

Spring MVC 3 and Apache Tiles 2
Spring MVC 3 – Tiles 2 Integration Tutorial

Spring MVC
Spring 3 MVC: Using @ModelAttribute in Your JSPs

Spring WS: WS-Security
Spring WS 2: Client-side WS-Security Using XWSS
Spring WS 2: Client-side WS-Security Using WSS4J
Spring-WS 2: WS-Security Using XWSS
Spring-WS 2: WS-Security Using WSS4J

Spring WS: XPath
Spring WS: Handling XML With XPath Using Jaxp13XPathTemplate
Spring WS: Handling XML With XPath Using JaxenXPathTemplate
Spring WS: Handling XML With XPath Using XPathExpression

Spring WS: Client
Spring MVC 3 – Accessing web services using JAX-WS
Spring WS – MVC: Implementing a Client Tutorial

Spring WS: Provider
Spring WS 2 and Spring 3 MVC Integration Tutorial
Spring WS: A Tutorial Using the Latest 2.0.0 RC2 Build

Spring MVC 3 and JDBC
Spring 3 MVC – JDBC Integration Tutorial

Spring MVC 3 and Hibernate Tutorials Series
Spring JPA: Many-To-One Association: Using Hibernate as the JPA Vendor
Spring JPA: One-To-Many Association: Using Hibernate as the JPA Vendor
Spring – Hibernate: Many-To-One Association – Explicitly Specify Join Table, Cascade, and Fetch
Spring – Hibernate: One-To-Many Association – Explicitly Specify Join Table, Cascade, and Fetch
Spring – Hibernate: Many-To-One Association
Spring – Hibernate: One-To-Many Association
Spring MVC 3, Hibernate Annotations, MySQL Integration Tutorial
Spring MVC 3, Hibernate Annotations, HSQLDB Integration Tutorial

Spring MVC 3 and Jasper
Spring MVC 3 – Jasper: How to Use JasperReportsMultiFormatView
Spring 3 MVC – Jasper: Using Two Sub-reports with Distinct Data Sources Tutorial
Spring 3 MVC – Jasper Integration Tutorial Without the View Support
Spring 3 MVC – Jasper: Sub-reports Using Two Data Sources Tutorial
Spring 3 MVC – Jasper: Sub-reports Tutorial
Spring 3 MVC – Jasper Integration Tutorial

Spring 3 and GWT
Spring and GWT: Security via Spring Security
Spring and GWT Integration using Maven and GWTHandler (Part 2)
Spring and GWT Integration using Maven and GWTHandler (Part 1)

Spring MVC 3 and DynamicJasper
Spring 3 – DynamicJasper – Hibernate Tutorial: Concatenating a DynamicReport
Spring 3 – DynamicJasper – Hibernate Tutorial: Concatenating a Subreport
Spring 3 – DynamicJasper – Hibernate Tutorial: Using Plain List
Spring 3 – DynamicJasper – Hibernate Tutorial: Using JRDataSource
Spring 3 – DynamicJasper – Hibernate Tutorial: Using HQL Query
Spring 3 MVC – DynamicJasper Integration Tutorial

Spring Security 3 and CAPTCHA
Spring Security 3: Integrating reCAPTCHA Service

Spring Security 3: OpenID
Spring Security 3 – OpenID with Javascript OpenID Selector
Spring Security 3 – OpenID Login with Google Provider
Spring Security 3 – OpenID Login with myOpenID Provider

Spring Security 3: ACL
Spring Security 3: Full ACL Tutorial (Part 4)
Spring Security 3: Full ACL Tutorial (Part 3)
Spring Security 3: Full ACL Tutorial (Part 2)
Spring Security 3: Full ACL Tutorial (Part 1)
Spring Security: Simple ACL using Expression-Based Access Control (Part 2)
Spring Security: Simple ACL using Expression-Based Access Control (Part 1)

Spring Security 3: Expressions
Spring Security 3 – MVC: Using Native Expression-Based Annotation Tutorial
Spring Security 3 – MVC: Using @Secured Annotation Tutorial

Spring MVC 3 and Spring Security
Spring JPA: Many-To-One Association: Using Hibernate as the JPA Vendor
Spring Security – MVC: Implementing a Single Entry Filter Tutorial
Spring Security – MVC: Querying the SessionRegistry
Spring Security 3 – MVC: Using a Simple User-Service Tutorial
Spring Security 3 – MVC Integration: Using A Custom Authentication Manager
Spring Security 3 – MVC Integration Tutorial (Part 2)
Spring Security 3 – MVC Integration Tutorial (Part 1)

Spring MVC 3 and jqGrid
Spring 3: Dynamic MVC using jqGrid and MongoDB
jqGrid and Spring 3 MVC Integration Tutorial

Blogger
How to customize your Google ads placement and position them in a custom Blogger template.
How to apply a custom Blogger Template

WordPress Recent Posts from specific category

here cat=1 is our category ID number and showposts=10 is our recent posts from specific category count. When you add this code to your sidebar.php file, you have to check your specific category ID from you admin panel, manage, categories.

global $post;
$recent = new WP_Query("cat=4&showposts=10");
while ($recent->have_posts())
{
$recent->the_post();

art_post_wrapper(
array(
'id' => art_get_post_id(),
'class' => art_get_post_class(),
//'thumbnail' => art_get_post_thumbnail(),
'title' => art_get_meta_option($post->ID, 'art_show_page_title') ? get_the_title() : '',
'before' => art_get_metadata_icons('edit', 'header'),
'content' => art_get_content(), // 'content' => 'My post content',
)
);
comments_template();

}
  print "<h2 class='art-postheader'>Latest News</h2>";
                    print "<ul>";
                     $recent = new WP_Query("cat=5&showposts=5");
                    while ($recent->have_posts())  
                {
                      $recent->the_post();
                            print "<li><a href=";
                            print the_permalink();
                            print " rel='bookmark'>";
                            print  the_title();
                            print   "</a></li>";
                      }
            
                            print "</ul>";