美文网首页
解决 JPA2.1 支持 group by 多个字段

解决 JPA2.1 支持 group by 多个字段

作者: aaron_ouyang | 来源:发表于2017-11-14 22:37 被阅读22次

    可以使用 Hibernate API 中的 @Formula 解决 group by 中多个字段的问题,代码如下:

    maven 依赖

            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-core</artifactId>
                <version>5.0.12.Final</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-jta_1.1_spec</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>5.0.12.Final</version>
                <exclusions>
                    <exclusion>
                        <groupId>org.apache.geronimo.specs</groupId>
                        <artifactId>geronimo-jta_1.1_spec</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
    

    entity 对象中添加 concat 属性

        @Formula("concat(date, receive_way)")
        private String concated;
    

    repo 中基于 concated 字段进行分组

            JPAQuery<?> query = new JPAQuery<Void>(em);
            QSettleAccount settleAccount = QSettleAccount.settleAccount;
    
            return query.select(
                    settleAccount.date,
                    settleAccount.receiveWay,
                    settleAccount.settleAmount.sum(),
                    settleAccount.procedureFee.sum())
                    .from(settleAccount)
                    .groupBy(settleAccount.concated)
                    .having(predicate)
                    .offset(0)
                    .limit(10)
                    .fetchResults();
    

    以上方式已经验证通过

    相关文章

      网友评论

          本文标题:解决 JPA2.1 支持 group by 多个字段

          本文链接:https://www.haomeiwen.com/subject/injqvxtx.html