Note: Mybatis Plus version 3.0.7 only started using Custom SQL + [Query Wrapper], low version can not be used, or honest SQL for conditional splicing.
2.0. Source code analysis
In the Wrapper < T > interface, there are the following methods
/** * Get custom SQL to simplify custom XML complexities * <p>Method of Use</p> * <p>`Custom SQL `+${ew.customSqlSegment}</p> * <p>1.Logical deletion requires splicing conditions (as previously customized)</p> * <p>2.Incidental entity in wrapper is not supported (wrapper's own entity is more cumbersome)</p> * <p>3.Usage ${ew.customSqlSegment} (No where label package, remember!)</p> * <p>4.ew Wapper defines aliases and can be replaced by itself</p> */ public abstract String getCustomSqlSegment();
Implemented in AbstractWrapper abstract class
@Override public String getCustomSqlSegment() { // Merge Segments Merge SQL Fragments for Return MergeSegments expression = getExpression(); if (Objects.nonNull(expression)) { NormalSegmentList normal = expression.getNormal(); String sqlSegment = getSqlSegment(); if (StringUtils.isNotEmpty(sqlSegment)) { if (normal.isEmpty()) { return sqlSegment; } else { return concatWhere(sqlSegment); } } } return StringUtils.EMPTY; } /** * Splicing `WHERE'before SQL * * @param sql sql * @return sql with where */ private String concatWhere(String sql) { return Constants.WHERE + " " + sql; }
2.1,dao
@Mapper public interface ReseDao extends BaseDao<ReseEntity> { /** * Paging query * @param page: mybatisPlus Native Paging Query, Query SQL will automatically splice Paging * @param queryWrapper: QueryWrapper Conditions, note that you need to specify the mybatis parameter with @Param("ew") * @return */ IPage<ReseEntity> getReseList(IPage<T> page, @Param("ew") QueryWrapper<ReseEntity> queryWrapper); }
2.2,xml
After the query SQL is written, instead of writing WHERE, add ${ew.customSqlSegment} after the SQL, and mybatis Plus will automatically add queries and splice them together.
Why ew: Mybatis Plus had Entity Wrapper before, and later versions differentiated Entity Wrapper into multiple Wrappers, such as Query Wrapper when querying, guessing that there might have been too many references through EW before, keeping the use of ew.
<select id="getReseList" resultMap="reseMap"> SELECT r.rese_id, r.rese_no, w.WORK_Name FROM t_s_db_rese r left join t_s_db_work w on r.WORK_id = w.WORK_id ${ew.customSqlSegment} </select>
2.3,service
/** * getPage(params, null, false): Method to splice the class of mybatis plus paging components * getWrapper(params): Method for splicing QueryWrapper conditional constructor */ @Override public PageData<ReseDTO> page(Map<String, Object> params) { IPage<ReseEntity> page = reservationDao.getReseList( getPage(params, null, false), getWrapper(params) ); return getPageData(page, ReseDTO.class); }