Hibernate Criteria - 在select语句中排除group by子句

时间:2016-06-27 09:04:58

标签: java hibernate

我已经在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

但是当我尝试在Hibernate Criteria中编写相同内容时,就像这样:

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")));

我从hibernate得到这个sql查询:

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

如何在Hibernate标准中复制原始SQL查询?

1 个答案:

答案 0 :(得分:0)

我能够使用以下查询解决此问题。工作就像一个魅力!

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));