Results 1 to 3 of 3

Thread: Getting a unique result

  1. #1
    Join Date
    Feb 2006
    Posts
    15

    Default Getting a unique result

    Hi everybody,

    This is an improvement proposition. On several occasions I needed to get a unique result out of a query; that is I expected to get only one result, and getting more than one would be considered an error that I would have to deal with.

    The Hibernate API offers different ways to implement this, the easiest one probably being to use a Query object and use the query.uniqueResult() method. Other ways involve the Criteria API.

    I haven't found any easy way to do so through the HibernateTemplate however. Did I miss it?
    Otherwise, I propose to add the following method to the HibernateTemplate class :

    Code:
    public Object uniqueResult(final String queryString, final Object[] values) throws DataAccessException {
    	try {
    		return (List) execute(new HibernateCallback() {
    			public Object doInHibernate(Session session) throws HibernateException {
    				Query queryObject = session.createQuery(queryString);
    				prepareQuery(queryObject);
    				if (values != null) {
    					for (int i = 0; i < values.length; i++) {
    						queryObject.setParameter(i, values[i]);
    					}
    				}
    				return queryObject.uniqueResult();
    			}
    		}, true);
    	} catch (NonUniqueResultException e) {
    		throw new IncorrectResultSizeDataAccessException(e.getMessage(), 1);
    	}
    }

    or:


    Code:
    public Object uniqueResult(final String queryString, final Object[] values) throws DataAccessException {
    	List results = find(queryString, values);
    	if (results.size() > 1)
    		throw new IncorrectResultSizeDataAccessException(1);
    	
    	return results.get(0);
    }

  2. #2
    Join Date
    Mar 2007
    Posts
    515

    Default

    Why don't you try this:
    Code:
    import org.springframework.dao.support.DataAccessUtils;
    ...
    Object someObject = DataAccessUtils.uniqueResult(getHibernateTemplate().find("your_query"));

  3. #3
    Join Date
    Sep 2006
    Location
    UK
    Posts
    8,424

    Default

    I think you are right. You'd have to call uniqueResult on the query to do this for you. There are a few things like this where you have to use the HibernateCallback. If you do want the change, JIRA would be your best bet.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •