往MybatisPlus添加一个分组统计的通用方法

public interface MyBaseMapper extends BaseMapper {

    //  @Deprecated 由于数据封装原因,请使用selectGroupCount
    // 试了下,用@MapKey,也不会。只能封装成<Object,GroupCountResult>,只能另写方法selectGroupCount了。
    // 麻是麻烦点。效果还是达到了
    @Deprecated
    List<GroupCountResult> groupCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper, @Param(Part.COLUMN) String column);
	
    default Map<Object, Integer> selectGroupCount(Wrapper<T> queryWrapper, String column) {
        List<GroupCountResult> selectResults = groupCount(queryWrapper, column);
        Map<Object, Integer> result = new HashMap<>();
        for (GroupCountResult selectResult : selectResults) {
            result.put(selectResult.getCountKey(), selectResult.getCountValue());
        }
        return result;
    }
 }
public class MyCountGroup extends AbstractMethod {


    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
        String selectSql = "SELECT %s FROM %s %s";
        // 正常按select * from xxx where xxx查,把查询的字段改成${就行了}
        String sql = String.format(selectSql, "${" + Part.COLUMN + "}",
                tableInfo.getTableName(), this.sqlWhereEntityWrapper(true, tableInfo));
		// 在上面的基础上包一层分组,
        String groupSqlTemplate = "<script>\nselect ${%s} as countKey,count(${%s}) as countValue from (%s) tmp group by ${%s} having ${%s} is not null\n</script>";
        String groupSql = String.format(groupSqlTemplate, Part.COLUMN, Part.COLUMN, sql, Part.COLUMN, Part.COLUMN);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, groupSql, modelClass);
        // 修改下返回值类型为GroupCountResult
        return this.addSelectMappedStatement(mapperClass, "groupCount", sqlSource, GroupCountResult.class, tableInfo);
    }
}

@Data
public class GroupCountResult {

    private Object countKey;

    private Integer countValue;
}

使用示例:

   public void doBusiness() {
        QueryWrapper<Uniter> wrapper = Q.queryNoDel();
        wrapper.eq("is_using", 1);
        Map<Object, Integer> repository_type = uniterMapper.selectGroupCount(wrapper, "repository_type");

        System.out.println(repository_type);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值