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