MyBatis-Plus工具使用之EntityWrapper解析

目录

  • EntityWrapper使用解析
  • EntityWrapper源码解读

EntityWrapper使用解析 1、项目中引入jar包,我这里使用Maven构建
com.baomidoumybatis-plus仓库最高版本号snapshotshttps://oss.sonatype.org/content/repositories/snapshots/

特别说明: Mybatis及Mybatis-Spring依赖请勿加入项目配置,以免引起版本冲突!!!Mybatis-Plus会自动帮你维护!
2、springboot项目中application.yml文件中加上
mybatisplus:enabled: truegeneric:enabled: truedialectType: mysql

传统SSM项目,修改配置文件,将mybatis的sqlSessionFactory替换成mybatis-plus的即可,mybatis-plus只做了一些功能的扩展:

3、创建Mapper、xml,创建Mapper时继承BaseMapper,xml正常(省略xml信息)
public interface UserMapper extends BaseMapper {}

4、实现类继承ServiceImpl
@Service@Slf4jpublic class UserServiceImpl extends ServiceImpl implements IUserService {public void queryUserList(UserDto dto){EntityWrapper ew = new EntityWrapper(); ew.where("deleted={0}", 1); ew.in("user_type", "1"); ew.eq("role", "1"); ew.eq("status", "1"); ew.orderBy("id"); ew.orderBy("created_time", true); log.info("selectList condition:{}", ew.getSqlSegment()); List userList = this.selectList(ew); }}

更多资料,请查看: mybaits-plus官方文档

EntityWrapper源码解读 mybatis plus内置了好多CRUD,其中 EntityWrapper这个类就是。
这个类是mybatis plus帮我们写好的好多接口,就如同我们在dao层写好方法在xml中实现一样。
那么这个友好的类给我们实现了哪些方法呐,今天我们来通过看看源码,来具体说说
/** * Copyright (c) 2011-2014, hubin (jobob@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */package com.baomidou.mybatisplus.mapper; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import com.baomidou.mybatisplus.enums.SqlLike; import com.baomidou.mybatisplus.exceptions.MybatisPlusException; import com.baomidou.mybatisplus.toolkit.ArrayUtils; import com.baomidou.mybatisplus.toolkit.CollectionUtils; import com.baomidou.mybatisplus.toolkit.MapUtils; import com.baomidou.mybatisplus.toolkit.SqlUtils; import com.baomidou.mybatisplus.toolkit.StringUtils; /** * * 条件构造抽象类,定义T-SQL语法 *
* * @author hubin , yanghu , Dyang , Caratacus * @Date 2016-11-7 */@SuppressWarnings("serial")public abstract class Wrapper implements Serializable { /*** 占位符*/private static final String PLACE_HOLDER = "{%s}"; private static final String MYBATIS_PLUS_TOKEN = "#{%s.paramNameValuePairs.%s}"; private static final String MP_GENERAL_PARAMNAME = "MPGENVAL"; private static final String DEFAULT_PARAM_ALIAS = "ew"; protected String paramAlias = null; /*** SQL 查询字段内容,例如:id,name,age*/protected String sqlSelect = null; /*** 实现了TSQL语法的SQL实体*/protected SqlPlus sql = new SqlPlus(); /*** 自定义是否输出sql为 WHERE OR AND OR OR*/protected Boolean isWhere; /*** 拼接WHERE后应该是AND还是OR*/protected String AND_OR = "AND"; private Map paramNameValuePairs = new HashMap<>(4); private AtomicInteger paramNameSeq = new AtomicInteger(0); /*** 兼容EntityWrapper** @return*/public T getEntity() {return null; } public String getSqlSelect() {if (StringUtils.isEmpty(sqlSelect)) {return null; }return stripSqlInjection(sqlSelect); } public Wrapper setSqlSelect(String sqlSelect) {if (StringUtils.isNotEmpty(sqlSelect)) {this.sqlSelect = sqlSelect; }return this; } /*** SQL 片段 (子类实现)*/public abstract String getSqlSegment(); public String toString() {String sqlSegment = getSqlSegment(); if (StringUtils.isNotEmpty(sqlSegment)) {sqlSegment = sqlSegment.replaceAll("#\\{" + getParamAlias() + ".paramNameValuePairs.MPGENVAL[0-9]+}", "\\?"); }return sqlSegment; } /*** * SQL中WHERE关键字跟的条件语句*
* * eg: ew.where("name='zhangsan'").where("id={0}","123"); * * 输出: WHERE (NAME='zhangsan' AND id=123)*
** @param sqlWhere where语句* @param params参数集* @return this*/public Wrapper where(String sqlWhere, Object... params) {sql.WHERE(formatSql(sqlWhere, params)); return this; } /*** * 等同于SQL的"field=value"表达式*
** @param column* @param params* @return*/public Wrapper eq(String column, Object params) {sql.WHERE(formatSql(String.format("%s = {0}", column), params)); return this; } /*** * 等同于SQL的"field <> value"表达式*
** @param column* @param params* @return*/public Wrapper ne(String column, Object params) {sql.WHERE(formatSql(String.format("%s <> {0}", column), params)); return this; } /*** * 等同于SQL的"field=value"表达式*
** @param params* @return*/@SuppressWarnings({"rawtypes", "unchecked"})public Wrapper allEq(Map params) {if (MapUtils.isNotEmpty(params)) {Iterator iterator = params.entrySet().iterator(); while (iterator.hasNext()) {Map.Entry entry = (Map.Entry) iterator.next(); Object value = https://www.it610.com/article/entry.getValue(); if (StringUtils.checkValNotNull(value)) {sql.WHERE(formatSql(String.format("%s = {0}", entry.getKey()), entry.getValue())); } } }return this; } /*** * 等同于SQL的"field>value"表达式*
** @param column* @param params* @return*/public Wrapper gt(String column, Object params) {sql.WHERE(formatSql(String.format("%s > {0}", column), params)); return this; } /*** * 等同于SQL的"field>=value"表达式*
** @param column* @param params* @return*/public Wrapper ge(String column, Object params) {sql.WHERE(formatSql(String.format("%s >= {0}", column), params)); return this; } /*** * 等同于SQL的"field ** @param column* @param params* @return*/public Wrapper lt(String column, Object params) {sql.WHERE(formatSql(String.format("%s < {0}", column), params)); return this; } /*** * 等同于SQL的"field<=value"表达式*
** @param column* @param params* @return*/public Wrapper le(String column, Object params) {sql.WHERE(formatSql(String.format("%s <= {0}", column), params)); return this; } /*** * AND 连接后续条件*
** @param sqlAnd and条件语句* @param params 参数集* @return this*/public Wrapper and(String sqlAnd, Object... params) {sql.AND().WHERE(formatSql(sqlAnd, params)); return this; } /*** * 使用AND连接并换行*
* * eg: ew.where("name='zhangsan'").and("id=11").andNew("statu=1"); 输出: WHERE* (name='zhangsan' AND id=11) AND (statu=1)*
** @param sqlAnd AND 条件语句* @param params 参数值* @return this*/public Wrapper andNew(String sqlAnd, Object... params) {sql.AND_NEW().WHERE(formatSql(sqlAnd, params)); return this; } /*** * 使用AND连接并换行*
* ** @return this*/public Wrapper and() {sql.AND_NEW(); return this; } /*** * 使用OR连接并换行*
** @return this*/public Wrapper or() {sql.OR_NEW(); return this; } /*** * 添加OR条件*
** @param sqlOror 条件语句* @param params 参数集* @return this*/public Wrapper or(String sqlOr, Object... params) {if (StringUtils.isEmpty(sql.toString())) {AND_OR = "OR"; }sql.OR().WHERE(formatSql(sqlOr, params)); return this; } /*** * 使用OR换行,并添加一个带()的新的条件*
* * eg: ew.where("name='zhangsan'").and("id=11").orNew("statu=1"); 输出: WHERE* (name='zhangsan' AND id=11) OR (statu=1)*
** @param sqlOrAND 条件语句* @param params 参数值* @return this*/public Wrapper orNew(String sqlOr, Object... params) {if (StringUtils.isEmpty(sql.toString())) {AND_OR = "OR"; }sql.OR_NEW().WHERE(formatSql(sqlOr, params)); return this; } /*** 【MyBatis-Plus工具使用之EntityWrapper解析】* SQL中groupBy关键字跟的条件语句*
* * eg: ew.where("name='zhangsan'").groupBy("id,name")*
** @param columns SQL 中的 Group by 语句,无需输入 Group By 关键字* @return this*/public Wrapper groupBy(String columns) {sql.GROUP_BY(columns); return this; } /*** * SQL中having关键字跟的条件语句*
* * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null")*
** @param sqlHaving having关键字后面跟随的语句* @param params参数集* @return EntityWrapper*/public Wrapper having(String sqlHaving, Object... params) {sql.HAVING(formatSql(sqlHaving, params)); return this; } /*** * SQL中orderby关键字跟的条件语句*
* * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null"* ).orderBy("id,name")*
** @param columns SQL 中的 order by 语句,无需输入 Order By 关键字* @return this*/public Wrapper orderBy(String columns) {sql.ORDER_BY(columns); return this; } /*** * SQL中orderby关键字跟的条件语句,可根据变更动态排序*
** @param columns SQL 中的 order by 语句,无需输入 Order By 关键字* @param isAsc是否为升序* @return this*/public Wrapper orderBy(String columns, boolean isAsc) {if (StringUtils.isNotEmpty(columns)) {sql.ORDER_BY(columns + (isAsc ? " ASC" : " DESC")); }return this; } /*** LIKE条件语句,value中无需前后%** @param column 字段名称* @param value匹配值* @return this*/public Wrapper like(String column, String value) {handerLike(column, value, SqlLike.DEFAULT, false); return this; } /*** NOT LIKE条件语句,value中无需前后%** @param column 字段名称* @param value匹配值* @return this*/public Wrapper notLike(String column, String value) {handerLike(column, value, SqlLike.DEFAULT, true); return this; } /*** 处理LIKE操作** @param column 字段名称* @param valuelike匹配值* @param isNot是否为NOT LIKE操作*/private void handerLike(String column, String value, SqlLike type, boolean isNot) {if (StringUtils.isNotEmpty(column) && StringUtils.isNotEmpty(value)) {StringBuilder inSql = new StringBuilder(); inSql.append(column); if (isNot) {inSql.append(" NOT"); }inSql.append(" LIKE {0}"); sql.WHERE(formatSql(inSql.toString(), SqlUtils.concatLike(value, type))); }} /*** LIKE条件语句,value中无需前后%** @param column 字段名称* @param value匹配值* @param type* @return this*/public Wrapper like(String column, String value, SqlLike type) {handerLike(column, value, type, false); return this; } /*** NOT LIKE条件语句,value中无需前后%** @param column 字段名称* @param value匹配值* @param type* @return this*/public Wrapper notLike(String column, String value, SqlLike type) {handerLike(column, value, type, true); return this; } /*** is not null 条件** @param columns 字段名称。多个字段以逗号分隔。* @return this*/public Wrapper isNotNull(String columns) {sql.IS_NOT_NULL(columns); return this; } /*** is not null 条件** @param columns 字段名称。多个字段以逗号分隔。* @return this*/public Wrapper isNull(String columns) {sql.IS_NULL(columns); return this; } /*** EXISTS 条件语句,目前适配mysql及oracle** @param value 匹配值* @return this*/public Wrapper exists(String value) {sql.EXISTS(value); return this; } /*** NOT EXISTS条件语句** @param value 匹配值* @return this*/public Wrapper notExists(String value) {sql.NOT_EXISTS(value); return this; } /*** IN 条件语句,目前适配mysql及oracle** @param column 字段名称* @param value逗号拼接的字符串* @return this*/public Wrapper in(String column, String value) {if (StringUtils.isNotEmpty(value)) {in(column, StringUtils.splitWorker(value, ",", -1, false)); }return this; } /*** NOT IN条件语句** @param column 字段名称* @param value逗号拼接的字符串* @return this*/public Wrapper notIn(String column, String value) {if (StringUtils.isNotEmpty(value)) {notIn(column, StringUtils.splitWorker(value, ",", -1, false)); }return this; } /*** IN 条件语句,目前适配mysql及oracle** @param column 字段名称* @param value匹配值 List集合* @return this*/public Wrapper in(String column, Collection value) {if (CollectionUtils.isNotEmpty(value))sql.WHERE(formatSql(inExpression(column, value, false), value.toArray())); return this; } /*** NOT IN 条件语句,目前适配mysql及oracle** @param column 字段名称* @param value匹配值 List集合* @return this*/public Wrapper notIn(String column, Collection value) {if (CollectionUtils.isNotEmpty(value))sql.WHERE(formatSql(inExpression(column, value, true), value.toArray())); return this; } /*** IN 条件语句,目前适配mysql及oracle** @param column 字段名称* @param value匹配值 object数组* @return this*/public Wrapper in(String column, Object[] value) {if (ArrayUtils.isNotEmpty(value))sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), false), value)); return this; } /*** NOT IN 条件语句,目前适配mysql及oracle** @param column 字段名称* @param value匹配值 object数组* @return this*/public Wrapper notIn(String column, Object... value) {if (ArrayUtils.isNotEmpty(value))sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), true), value)); return this; } /*** 获取in表达式** @param column 字段名称* @param value集合List* @param isNot是否为NOT IN操作*/private String inExpression(String column, Collection value, boolean isNot) {if (StringUtils.isNotEmpty(column) && CollectionUtils.isNotEmpty(value)) {StringBuilder inSql = new StringBuilder(); inSql.append(column); if (isNot) {inSql.append(" NOT"); }inSql.append(" IN "); inSql.append("("); int size = value.size(); for (int i = 0; i < size; i++) {inSql.append(String.format(PLACE_HOLDER, i)); if (i + 1 < size) {inSql.append(","); }}inSql.append(")"); return inSql.toString(); }return null; } /*** betwwee 条件语句** @param column 字段名称* @param val1* @param val2* @return this*/public Wrapper between(String column, Object val1, Object val2) {sql.WHERE(formatSql(String.format("%s BETWEEN {0} AND {1}", column), val1, val2)); return this; } /*** NOT betwwee 条件语句** @param column 字段名称* @param val1* @param val2* @return this*/public Wrapper notBetween(String column, Object val1, Object val2) {sql.WHERE(formatSql(String.format("%s NOT BETWEEN {0} AND {1}", column), val1, val2)); return this; } /*** 为了兼容之前的版本,可使用where()或and()替代** @param sqlWhere where sql部分* @param params参数集* @return this*/public Wrapper addFilter(String sqlWhere, Object... params) {return and(sqlWhere, params); } /*** * 根据判断条件来添加条件语句部分 使用 andIf() 替代*
* * eg: ew.filterIfNeed(false,"name='zhangsan'").where("name='zhangsan'")* .filterIfNeed(true,"id={0}",22)* * 输出: WHERE (name='zhangsan' AND id=22)*
** @param need是否需要添加该条件* @param sqlWhere 条件语句* @param params参数集* @return this*/public Wrapper addFilterIfNeed(boolean need, String sqlWhere, Object... params) {return need ? where(sqlWhere, params) : this; } /*** * SQL注入内容剥离*
** @param value 待处理内容* @return this*/protected String stripSqlInjection(String value) {return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", ""); } /*** * 格式化SQL*
** @param sqlStr SQL语句部分* @param params 参数集* @return this*/protected String formatSql(String sqlStr, Object... params) {return formatSqlIfNeed(true, sqlStr, params); } /*** * 根据需要格式化SQL
*
* Format SQL for methods: EntityWrapper.where/and/or...("name={0}", value); * ALL the {i} will be replaced with #{MPGENVALi}
*
* ew.where("sample_name={0}", "haha").and("sample_age > {0}* and sample_age< {1}", 18, 30) TO* sample_name=#{MPGENVAL1} and sample_age> #{MPGENVAL2} and* sample_age< #{MPGENVAL3}
*
** @param need是否需要格式化* @param sqlStr SQL语句部分* @param params 参数集* @return this*/protected String formatSqlIfNeed(boolean need, String sqlStr, Object... params) {if (!need || StringUtils.isEmpty(sqlStr)) {return null; }// #200if (ArrayUtils.isNotEmpty(params)) {for (int i = 0; i < params.length; ++i) {String genParamName = MP_GENERAL_PARAMNAME + paramNameSeq.incrementAndGet(); sqlStr = sqlStr.replace(String.format(PLACE_HOLDER, i),String.format(MYBATIS_PLUS_TOKEN, getParamAlias(), genParamName)); paramNameValuePairs.put(genParamName, params[i]); }}return sqlStr; } /*** * 自定义是否输出sql开头为 `WHERE` OR `AND` OR `OR`*
** @param bool* @return this*/public Wrapper isWhere(Boolean bool) {this.isWhere = bool; return this; } /*** * SQL LIMIT*
** @param begin 起始* @param end结束* @return this*/public Wrapper limit(int begin, int end) {sql.LIMIT(begin, end); return this; } /*** Fix issue 200.** @return* @since 2.0.3*/public Map getParamNameValuePairs() {return paramNameValuePairs; } public String getParamAlias() {return StringUtils.isEmpty(paramAlias) ? DEFAULT_PARAM_ALIAS : paramAlias; } /*** * 调用该方法时 应当在吃初始化时优先设置该值 不要重复设置该值 要不然我就给你抛异常了*
** @param paramAlias* @return*/public Wrapper setParamAlias(String paramAlias) {if (StringUtils.isNotEmpty(getSqlSegment())) {throw new MybatisPlusException("Error: Please call this method when initializing!"); }if (StringUtils.isNotEmpty(this.paramAlias)) {throw new MybatisPlusException("Error: Please do not call the method repeatedly!"); }this.paramAlias = paramAlias; return this; }}

最后说一句,阅读源码,你会收获很多,看到别人的处理方式,你会有很大进步的。哈哈,今天你学到了吗
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读