Grails Groovy Hibernate | Hibernate Criteria Builder | Projection | Custom Projection | Group By Projection | PropertyProjection.
It's easy to add projection custom. We can add custom projection and custom group by property.
But you want to make it simpler then you can use below function easily:
It's easy to add projection custom. We can add custom projection and custom group by property.
import org.hibernate.criterion.Projections import org.hibernate.criterion.Projection import org.hibernate.criterion.PropertyProjection import org.hibernate.Criteria import org.hibernate.criterion.CriteriaQuery import org.hibernate.HibernateException org.hibernate.criterion.ProjectionList projectionList = [] ProjectionList projectionList = [] projectionList.add(new PropertyProjection("id") { @Override public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { return "this_.id as y0_" } }) projectionList.add(new PropertyProjection("created") { @Override public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { return "MAX(this_.created) as y1_" } }) projectionList.add(Projections.groupProperty("belongsTo.id")) PropertyProjection groupBy = new PropertyProjection("id", true) { @Override public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException { return "belongsto1_.id as y1_" } @Override public String toGroupSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { return "belongsto1_.id" } } projectionList.add(groupBy) Closure closure = { setProjection(projectionList) } List list = Domain.createCriteria().list { and closure }
But you want to make it simpler then you can use below function easily:
import org.hibernate.criterion.CriteriaSpecification import org.hibernate.criterion.Projections import org.hibernate.type.DoubleType import org.hibernate.type.Type resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP) projections { groupProperty("id", "id") groupProperty("name", "name") addProjectionToList(Projections.sqlProjection( "sum(id * 0.2) as totalPrice", ["totalPrice"] as String[], [DoubleType.INSTANCE] as Type[], ), "complexSqlCalculation") }