Recently I create a new restriction to find entities by PK using the clausule IN.
-----
package com.ig.ibest.persistence.hibernate.criterion;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.criterion.CriteriaQuery;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.hibernate.engine.TypedValue;
/**
* Constraint to find by ID using clausule IN
*
* @author hnqoliveira
*
*/
public class IdentifierInExpression implements Criterion {
private static final long serialVersionUID = -3120283684494528083L;
private final Object[] values;
private Criterion delegate;
public IdentifierInExpression(List<Object> values) {
this.values = values.toArray();
}
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
String idProp = getIdProperty(criteria, criteriaQuery);
delegate = Restrictions.in(idProp, values);
return delegate.toSqlString(criteria, criteriaQuery);
}
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
return delegate.getTypedValues(criteria, criteriaQuery);
}
@Override
public String toString() {
return delegate.toString();
}
/**
* Retrieve propertyName that represent the Identifier of table
*
* @param criteria
* @param criteriaQuery
* @return
*/
private String getIdProperty(Criteria criteria, CriteriaQuery criteriaQuery) {
return criteriaQuery.getFactory().getIdentifierPropertyName(criteriaQuery.getEntityName(criteria));
}
}
------
I create the method in my GenericDAO
public List<T> find(List<ID> ids) throws DAOException {
if(ids.size() == 1) {
T obj = find(ids.get(0));
return (obj != null)?Collections.<T>singletonList(obj):Collections.<T>emptyList();
}
try {
Criteria criteria = createCriteria().add(new IdentifierInExpression(ids));
return criteria.list();
} catch (Exception e) {
throw new DAOException("An error occurs while find entities of class " + clazz+" with ids "+ids, e);
}
}
Comments