Mybatis-plus在原有的xml配置文件的select查詢語句中動態追加查詢條件


一、適用場景

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中傳入的值" 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM