Utilizando funções aninhadas no Hibernate
Twitter!
Quem utiliza Criteria já deve ter precisado utilizar funções aninhadas ( como sum(abs(propriedade)) ). Infelizmente a class Projections não dispoem deste recurso, e a classe que implementa as agregações ( AggregateProjection ) não foi projetada pensando nisso.
Baseado na class AggregateProjection implementei uma solução com um construtor que recebe um array de string com as funções a serem aninhadas na ordem do array
JAVA:
-
package br.com.dclick.hibernate.criterion;
-
-
import org.hibernate.Criteria;
-
import org.hibernate.HibernateException;
-
import org.hibernate.criterion.CriteriaQuery;
-
import org.hibernate.criterion.SimpleProjection;
-
import org.hibernate.type.Type;
-
-
public class AggregateFunctionsProjection extends SimpleProjection {
-
-
-
this.aggregate = aggregate;
-
this.propertyName = propertyName;
-
}
-
-
return this.mountSql(this.propertyName).toString();
-
}
-
-
public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
-
return new Type[] { criteriaQuery.getType(criteria, propertyName) };
-
}
-
-
public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery) throws HibernateException {
-
return this.mountSql( criteriaQuery.getColumn(criteria, propertyName) )
-
.append(" as y")
-
.append(loc)
-
.append('_')
-
.toString();
-
}
-
-
-
-
for (int i = 0; i <this.aggregate.length; i++) {
-
start.append( this.aggregate[i] + "(" );
-
end.append( ")" );
-
}
-
-
return start.append(property).append(end);
-
-
}
-
-
}
Pronto. Agora e so adicionar ao seu criterio:
JAVA:
-
-
HibernateSessionFactory.getSession()
-
.createCriteria(Produto.class)
-
.setProjection( new AggregateFunctionsProjection(funcoes, "nomeDaPropriedadeDaSuaClasse") )
-
.list();
2 comentários para “Utilizando funções aninhadas no Hibernate”
Muito bom!. Já estou utilizando…
Cara, que dicas boas de hibernate existem no teu site.
Parabens!

