如题spring-boot + Mybatis plus遇到一个需要自定义sql语句进行查询的需求,同时适配框架的分页需要,进行了一些尝试终于调通,关键步骤记录一下:
exampleMapper.java文件
package com.example.mapper;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neworder.common.core.web.mapper.BaseMapperPlus;
import com.neworder.example.domain.Template;
public interface TemplateMapper extends BaseMapperPlus<TemplateMapper, Template, Template> {
Page<Template> selectExample(Page<Template> page, @Param(Constants.WRAPPER) LambdaQueryWrapper<Template> lqw);
}
这里返回类型直接使用Page<类型>即可,关键点是参数中@Param(Constants.WRAPPER),跟踪代码可以发现,其默认值为'ew',所以在mapper.xml中也需要使用ew作为lqw参数来写sql,否则会报找不到ew的错误,可能是mybatis plus分页流程中固定的处理步骤,没有深究.
exampleMapper.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neworder.example.mapper.TemplateMapper">
<select id="selectExample" parameterType="Template" resultMap="TemplateResult">
select example.template_id from example
JOIN (
SELECT template_id
FROM example2
GROUP BY template_id
HAVING COUNT(template_id) > 0
) AS example2_filtered ON example.template_id = example2_filtered.template_id
${ew.customSqlSegment}
order by example.template_id DESC
</select>
</mapper>
这里的关键点是必须使用 ${ew.customSqlSegment},ew为调用函数时传入的lqw参数,但是由于mybatis plus内部处理的原因,这里需要使用ew进行参数传递,变量名固定,不过不影响使用。另外就是${ew.customSqlSegment}解析成sql语句会自带WHERE语句,所以在写xml时就**不要写<where>**了
函数调用
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
....
@Override
public TableDataInfo<Template> selectExample(Template template, PageQuery pageQuery) {
LambdaQueryWrapper<Template> lqw = new LambdaQueryWrapper<Template>()
.eq(StringUtils.isNotBlank(template.getCategory()), Template::getCategory, template.getCategory())
.like(StringUtils.isNotBlank(template.getTemplateName()), Template::getTemplateName, template.getTemplateName());
// 执行自定义查询
Page<Template> resultPage = templateMapper.selectExample(pageQuery.build(), lqw);
return TableDataInfo.build(resultPage);
}
这里可以按照正常的selectPage写法来写,原因就是我们在定义exampleMapper.java 中的接口时已经返回了Page类型的值,并且也传入了lqw进行解析,实测可以正常运行。