一、适用场景
1、使用了xml形式的mapper。
2、不想在select查询中大量使用<if>标签来判断条件是否存在而加入条件。
二、步骤
1、自定义wrapper继承QueryWrapper:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.shiro.util.StringUtils; public class CustomWrapper<T> extends QueryWrapper<T> { /** * ifSql记录自定义追加的条件 */ private String ifSql; /** * 赋值给ifSql * @return */ public CustomWrapper init(){ String sqlSegment = getSqlSegment(); if (StringUtils.hasText(sqlSegment)){ this.ifSql = "and" + getSqlSegment(); } return this; } public String getIfSql() { return this.ifSql; } //自定义eq、like等等方法,动态判断是否要加入条件 public CustomWrapper eq(String column,String val){ this.eq(StringUtils.hasText(val),column,val); return this; } public CustomWrapper like(String column,String val){ this.like(StringUtils.hasText(val),column,val); return this; } public CustomWrapper ge(String column,String val){ this.ge(StringUtils.hasText(val),column,val); return this; } public CustomWrapper le(String column,String val){ this.le(StringUtils.hasText(val),column,val); return this; } }
2、在mapper.java接口中定义方法:
@Mapper public interface IApplyInfoMapper extends CustomizedBaseMapper<ApplyInfo> { List<ApplyInfo> getApplyList(@Param(Constants.WRAPPER) Wrapper ew); //... }
3、在xml中加入标识符 ${ew.ifSql}
<select id="getAllApplyInfoList" resultMap="allApplyInfoMapper"> SELECT ... FROM b LEFT JOIN w ON b.wid= w.id LEFT JOIN n ON b.nid= n.id WHERE b.ZT = '1' ${ew.ifSql} </select>
4、在service层加入mybatis-plus自定义wrapper条件
@Service public class ApplyInfoServiceImpl extends ServiceImpl<IApplyInfoMapper,ApplyInfo> implements IApplyInfoService { @Autowired private IApplyInfoMapper mapper; @Override public PageInfo queryPage(PageInfo pageInfo) { Page page = PageUtils.getPage(pageInfo); CustomWrapper<ApplyInfo> wrapper = getCustomWrapper(pageInfo); List<ApplyInfo> list = mapper.getApplyList(wrapper.init()); PageUtils.setPageInfoProperty(pageInfo,page,list); return pageInfo; } /** * 这里的我将pageInfo为传入的条件 * @return */ private CustomWrapper<ApplyInfo> getCustomWrapper(PageInfo pageInfo) { CustomWrapper<ApplyInfo> wrapper = new CustomWrapper<>(); wrapper.eq("b.id",pageInfo.getProperty1()) return wrapper; } ...... }
5、最终执行sql语句为:
SELECT ... FROM b LEFT JOIN w ON b.wid= w.id LEFT JOIN n ON b.nid= n.id WHERE b.ZT = '1' AND b.id="这里为你在service中传入的值"