import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableFieldInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.reflection.property.PropertyNamer;
public List<Book> bookSum() {
QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
.gt(Book::getId, 1)
.lt(Book::getNumOne, 10010)
.gt(Book::getNumTow, 10000)
;
addSumSql(Book.class, queryWrapper, Book::getNumOne, Book::getNumTow);
Book sumInfo = this.bookMapper.selectOne(queryWrapper);
return Collections.singletonList(sumInfo);
}
@SafeVarargs
private final <E> void addSumSql(Class<E> entityClass, QueryWrapper<E> queryWrapper, SFunction<E, ?>... sumFieldFns) {
TableInfo tableInfo = TableInfoHelper.getTableInfo(entityClass);
Assert.notNull(tableInfo, "实体的表信息不存在," + entityClass.getName());
List<String> fieldList = new ArrayList<>();
for (SFunction<E, ?> esFunction : sumFieldFns) {
LambdaMeta meta = LambdaUtils.extract(esFunction);
String fieldName = PropertyNamer.methodToProperty(meta.getImplMethodName());
fieldList.add(fieldName);
}
List<TableFieldInfo> tableFieldInfoList = tableInfo.getFieldList().stream().filter(field -> fieldList.contains(field.getProperty()))
.collect(Collectors.toList());
Assert.notEmpty(tableFieldInfoList, "表字段信息为空," + entityClass.getName());
String sumSelectSql = tableFieldInfoList.stream().map(tableFieldInfo -> "SUM(" + tableFieldInfo.getColumn() +") AS " + tableFieldInfo.getColumn())
.collect(Collectors.joining(","));
queryWrapper.select(sumSelectSql);
}
输出的SQL如下:
[nio-8080-exec-1] c.e.demo.mapper.BookMapper.selectList : ==> Preparing: SELECT SUM(num_one) AS num_one,SUM(num_tow) AS num_tow FROM book WHERE (id > ? AND num_one < ? AND num_tow > ?)
[nio-8080-exec-1] c.e.demo.mapper.BookMapper.selectList : ==> Parameters: 1(Integer), 10010(Integer), 10000(Integer)
注:通过使用MyBatisPlus和ibatis提供的方法来获取表字段名,进行sum语句的拼接,从而达到sum函数的调用 。此方法可在3.5.0以上版本,其它版本可自行改动,故会有版本升级带来的不兼容性。