Akin_Glen Akin_Glen - 4 months ago 23
Java Question

Hibernate Criteria - Excluding group by clause in the select statement

I've written this in sql server:

select max(processed_trans_id) from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id


But when I try to write the same in Hibernate Criteria, like this:

DetachedCriteria dCriteria = DetachedCriteria.forClass(EquityTransaction.class)
.add(Restrictions.eq("clientCompany.id", sb.getClientCompany().getId()))
.add(Restrictions.le("transactionDate", sb.getQualifyDate()))
.setProjection(Projections.projectionList()
.add(Projections.max("processedTransaction.id"), "processedTransaction.id")
.add(Projections.groupProperty("holderCompanyAccount.id")));


I get this as the sql query from hibernate:

select max(processed_trans_id), comp_acct_id from EQUITY_TRANSACTION where transaction_date <= '2016-06-22' and company_id=75 group by comp_acct_id


How do I replicate the original SQL query in Hibernate criteria?

Answer

I was able to resolve this using the following query. Worked like a charm!

DetachedCriteria dCriteriaEt1 = DetachedCriteria.forClass(EquityTransaction.class, "et1")
                    .add(Restrictions.eq("clientCompany.id", decldDvd.getClientCompany().getId()))
                    .add(Restrictions.le("transactionDate", decldDvd.getQualifyDate()))
                    .setProjection(Projections.projectionList()
                            .add(Projections.max("processedTransaction.id"), "processedTransaction.id"))
                    .add(Restrictions.eqProperty("et1.holderCompanyAccount.id", "et2.holderCompanyAccount.id"));

            logger.info("Retrieving all qualified company account balances...");
            Criteria getQualifiedBalances = dao.getSession().createCriteria(EquityTransaction.class, "et2")
                    .add(Subqueries.propertyIn("processedTransaction.id", dCriteriaEt1))
                    .add(Restrictions.gt("balance", 0l))
                    .setProjection(Projections.projectionList()
                            .add(Projections.property("holderCompanyAccount.id"),"holderCompanyAccount.id")
                            .add(Projections.property("balance"), "balance"))
                    .addOrder(Order.asc("holderCompanyAccount.id"))
                    .addOrder(Order.desc("processedTransaction.id"))
                    .setResultTransformer(new AliasToBeanNestedResultTransformer(EquityTransaction.class));