mybatis-plus 聚合查询

原因

由于查询条件太多懒得写xml
在已经写好的LambdaQueryWrapper查询条件下,封装groupCount类似语句

代码

使用

  LambdaQueryWrapper<DBEntity> query = Wrappers.lambdaQuery();
  List<DBEntity> count = baseMapper.groupCount(query, col(DBEntity::getSomeThing));

col方法

private String col(SFunction<DBEntity, ?> column) {
    SerializedLambda resolve = LambdaUtils.resolve(column);
    Map<String, ColumnCache> columnMap = LambdaUtils.getColumnMap(resolve.getImplClassName());
    String implMethodName = resolve.getImplMethodName();
    ColumnCache columnCache = columnMap.get(StringUtils.resolveFieldName(implMethodName).toUpperCase());
    return columnCache.getColumn();
}

mapper接口

List<DBEntity> groupCount(@Param(Constants.WRAPPER) Wrapper<DBEntity> userWrapper, @Param("col") String col);

xml文件

    <select id="groupCount" resultType="DBEntity">
        select count(${col}) as count,${col} from t_alert_config ${ew.customSqlSegment}
        group by ${col}
    </select>
  class DBEntity{
        @TableField(value = "count", strategy = FieldStrategy.IGNORED, exist = false, select = false)
        private Long count;
        //数据库实体映射字段
        private String someThing;

        public Long getCount() {
            return count;
        }

        public DBEntity setCount(Long count) {
            this.count = count;
            return this;
        }

        public String getSomeThing() {
            return someThing;
        }

        public DBEntity setSomeThing(String someThing) {
            this.someThing = someThing;
            return this;
        }
    }

结果

SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@154ce972] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1822440743 wrapping com.mysql.jdbc.JDBC4Connection@693ed572] will not be managed by Spring
==>  Preparing: select count(case_id) as count,case_id from xxxx WHERE dept_num = ? group by case_id 
==> Parameters: 01001001(String)
<==    Columns: count, case_id
<==        Row: 996, 0
<==        Row: 1, 34
<==        Row: 1, 35
<==      Total: 3
posted @   _Y_h  阅读(591)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示