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); }


Reply With Quote