Grupo por mes con criterios de Hibernación
Estoy tratando de obtener un informe utilizando Criteria y ProjectionList, y soy bastante nuevo usando esto a través de hibernate. Así que tengo este modelo:
private Long _userId;
private Category _category;
private Long _companyId;
private Double _amount;
private Date _date;
Y construyo la consulta usando esto:
public List sumPaymentsByUserCategoryPeriod(Category category, Long userId,Integer period){
GregorianCalendar from = new GregorianCalendar();
from.add(Calendar.MONTH, -period);
List<CategoryAmount> resultDTO= new ArrayList<CategoryAmount>();
Criteria criteria = getSession().createCriteria(Payment.class);
criteria.add(Restrictions.eq("_category", category));
criteria.add(Restrictions.eq("_userId",userId));
criteria.add(Restrictions.between("_date", from.getTime(), new Date()));
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.sum("_amount"));
projectionList.add(Projections.groupProperty("_date"));
criteria.setProjection(projectionList);
return criteria.list();
}
Básicamente este método recibe una Categoría y un userId para filtrar los registros de pagos y un período, que indicará cuántos meses desde ahora hasta atrás quiero sumar. ¿Cómo puedo obtener el resultado de la suma agrupada por meses?
Cualquier ayuda o consejo lo apreciaré!
2 answers
Encontré la respuesta, y es bastante simple. Cambié el "groupProperty" en los criterios de ProjectionList para esto:
projectionList.add(Projections.sqlGroupProjection(
"month({alias}.DATE) as month, year({alias}.DATE) as year",
"month({alias}.DATE), year({alias}.DATE)",
new String[]{"month","year"},
new Type[] {Hibernate.DOUBLE}));
Bien. Explicaré la proyección del grupo SQL. El primer argumento es la parte de la consulta después de la "select", por ejemplo:
Select [firstPartOfSqlGroupProjection] * boo;
El "{alias}" es el alias que los hibernadores usan en la consulta para referirse a una tabla.
El segundo argumento de la función sqlGroupProjection es el group by criteria, el tercer argumento son los nombres de columna que obtendrás del grupo por y finalmente, el tipo de datos que usarás.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-02 15:09:33
Puede usar una SqlQuery en hibernación, aquí hay un ejemplo:
public List<MonthlyPoint> groupByMonth(ChartRequest request){
SQLQuery query = getSession().createSQLQuery("SELECT \n" +
"sum(this_.amount) as amount, \n" +
"extract(month from this_.fecha) as month, \n" +
"extract(year from this_.fecha) as year\n" +
"FROM jornada this_ \n" +
"GROUP BY \n" +
"month, \n" +
"year \n" +
"ORDER BY \n" +
"year asc, \n" +
"month asc");
query.setResultTransformer(Transformers.aliasToBean(MonthlyPoint.class));
return query.list();
}
public class MonthlyPoint {
private Double year;
private Double month;
private Double amount;
//-- getters and setters here --
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-29 23:37:29