Friday, February 8, 2008

Named Query Setup

this works for both hql and native query
/**
* Return a list of objects using a named query.
*
* @param queryName name of the query to be run
* @param parameterMap map of parameter names and values
* @return a List of all objects returned by the query
*/
protected List executeNamedQuery(String queryName,
Map parameterMap) {
try {
queryName = getPersistentClass().getName() + "." + queryName;
Query query = currentSession().getNamedQuery(queryName);
prepareQuery(query);
for (Map.Entry entry : parameterMap.entrySet()) {
applyNamedParameterToQuery(query, entry.getKey(), entry.getValue());
}
List list = query.list();
return list;
} catch (DataAccessException e) {
throw e;
}
}


/**
* Apply the given name parameter to the given Query object.
*
* @param query the Query object
* @param paramName the name of the parameter
* @param value the value of the parameter
* @throws org.hibernate.HibernateException
* if thrown by the Query object
*/
protected void applyNamedParameterToQuery(Query query, String paramName, Object value)
throws HibernateException {

if (value instanceof Collection) {
query.setParameterList(paramName, (Collection) value);
} else if (value instanceof Object[]) {
query.setParameterList(paramName, (Object[]) value);
} else {
query.setParameter(paramName, value);
}
}

protected void prepareQuery(Query query) {
SessionFactoryUtils.applyTransactionTimeout(query,
sessionFactory);
}

MAPPING EXAMPLE