Hibernate : uniqueResult

when query using hql or criteria is prepared it can be executed by calling below 2 methods
1. list()
2. uniqueResult()

If list method is invoked it is required to check the list size and based on list size result is returned. In some cases where we expect only one match in the table, for example if we need to check username and password and return the result, uniqueResult() method is helpful. The unique result method is Convenience method to return a single instance that matches the query, or null if the query returns no results.

If List is used this much coding is required:
List userList = criteria.list();
if(!userList.isEmpty()){
return (Login) userList.get(0);
}
return null;

If uniqueResult is used it can be reduced to
return (Login) criteria.uniqueResult();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s