文章详情

短信预约-IT技能 免费直播动态提醒

请输入下面的图形验证码

提交验证

短信预约提醒成功

MyBatis-Plus工具使用之EntityWrapper解析

2024-04-02 19:55

关注

EntityWrapper使用解析

1、项目中引入jar包,我这里使用Maven构建

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>仓库最高版本号</version>
</dependency>
<!--快照版本使用,正式版本无需添加此仓库-->
<repository>
    <id>snapshots</id>
    <url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>

特别说明: Mybatis及Mybatis-Spring依赖请勿加入项目配置,以免引起版本冲突!!!Mybatis-Plus会自动帮你维护!

2、springboot项目中application.yml文件中加上

mybatisplus:
  enabled: true
  generic:
    enabled: true
  dialectType: mysql

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

<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 自动扫描Mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:mybatis
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;
 

@SuppressWarnings("serial")
public abstract class Wrapper<T> 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;
    
    protected String sqlSelect = null;
    
    protected SqlPlus sql = new SqlPlus();
    
    protected Boolean isWhere;
    
    protected String AND_OR = "AND";
    private Map<String, Object> paramNameValuePairs = new HashMap<>(4);
    private AtomicInteger paramNameSeq = new AtomicInteger(0);
 
    
    public T getEntity() {
        return null;
    }
 
    public String getSqlSelect() {
        if (StringUtils.isEmpty(sqlSelect)) {
            return null;
        }
        return stripSqlInjection(sqlSelect);
    }
 
    public Wrapper<T> setSqlSelect(String sqlSelect) {
        if (StringUtils.isNotEmpty(sqlSelect)) {
            this.sqlSelect = sqlSelect;
        }
        return this;
    }
 
    
    public abstract String getSqlSegment();
 
    public String toString() {
        String sqlSegment = getSqlSegment();
        if (StringUtils.isNotEmpty(sqlSegment)) {
            sqlSegment = sqlSegment.replaceAll("#\\{" + getParamAlias() + ".paramNameValuePairs.MPGENVAL[0-9]+}", "\\?");
        }
        return sqlSegment;
    }
 
    
    public Wrapper<T> where(String sqlWhere, Object... params) {
        sql.WHERE(formatSql(sqlWhere, params));
        return this;
    }
 
    
    public Wrapper<T> eq(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s = {0}", column), params));
        return this;
    }
 
    
    public Wrapper<T> ne(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s <> {0}", column), params));
        return this;
    }
 
    
    @SuppressWarnings({"rawtypes", "unchecked"})
    public Wrapper<T> allEq(Map<String, Object> params) {
        if (MapUtils.isNotEmpty(params)) {
            Iterator iterator = params.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) iterator.next();
                Object value = entry.getValue();
                if (StringUtils.checkValNotNull(value)) {
                    sql.WHERE(formatSql(String.format("%s = {0}", entry.getKey()), entry.getValue()));
                }
 
            }
 
        }
        return this;
    }
 
    
    public Wrapper<T> gt(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s > {0}", column), params));
        return this;
    }
 
    
    public Wrapper<T> ge(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s >= {0}", column), params));
        return this;
    }
 
    
    public Wrapper<T> lt(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s < {0}", column), params));
        return this;
    }
 
    
    public Wrapper<T> le(String column, Object params) {
        sql.WHERE(formatSql(String.format("%s <= {0}", column), params));
        return this;
    }
 
    
    public Wrapper<T> and(String sqlAnd, Object... params) {
        sql.AND().WHERE(formatSql(sqlAnd, params));
        return this;
    }
 
    
    public Wrapper<T> andNew(String sqlAnd, Object... params) {
        sql.AND_NEW().WHERE(formatSql(sqlAnd, params));
        return this;
    }
 
    
    public Wrapper<T> and() {
        sql.AND_NEW();
        return this;
    }
 
    
    public Wrapper<T> or() {
        sql.OR_NEW();
        return this;
    }
 
    
    public Wrapper<T> or(String sqlOr, Object... params) {
        if (StringUtils.isEmpty(sql.toString())) {
            AND_OR = "OR";
        }
        sql.OR().WHERE(formatSql(sqlOr, params));
        return this;
    }
 
    
    public Wrapper<T> orNew(String sqlOr, Object... params) {
        if (StringUtils.isEmpty(sql.toString())) {
            AND_OR = "OR";
        }
        sql.OR_NEW().WHERE(formatSql(sqlOr, params));
        return this;
    }
 
    
    public Wrapper<T> groupBy(String columns) {
        sql.GROUP_BY(columns);
        return this;
    }
 
    
    public Wrapper<T> having(String sqlHaving, Object... params) {
        sql.HAVING(formatSql(sqlHaving, params));
        return this;
    }
 
    
    public Wrapper<T> orderBy(String columns) {
        sql.ORDER_BY(columns);
        return this;
    }
 
    
    public Wrapper<T> orderBy(String columns, boolean isAsc) {
        if (StringUtils.isNotEmpty(columns)) {
            sql.ORDER_BY(columns + (isAsc ? " ASC" : " DESC"));
        }
        return this;
    }
 
    
    public Wrapper<T> like(String column, String value) {
        handerLike(column, value, SqlLike.DEFAULT, false);
        return this;
    }
 
    
    public Wrapper<T> notLike(String column, String value) {
        handerLike(column, value, SqlLike.DEFAULT, true);
        return this;
    }
 
    
    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)));
        }
    }
 
    
    public Wrapper<T> like(String column, String value, SqlLike type) {
        handerLike(column, value, type, false);
        return this;
    }
 
    
    public Wrapper<T> notLike(String column, String value, SqlLike type) {
        handerLike(column, value, type, true);
        return this;
    }
 
    
    public Wrapper<T> isNotNull(String columns) {
        sql.IS_NOT_NULL(columns);
        return this;
    }
 
    
    public Wrapper<T> isNull(String columns) {
        sql.IS_NULL(columns);
        return this;
    }
 
    
    public Wrapper<T> exists(String value) {
        sql.EXISTS(value);
        return this;
    }
 
    
    public Wrapper<T> notExists(String value) {
        sql.NOT_EXISTS(value);
        return this;
    }
 
    
    public Wrapper<T> in(String column, String value) {
        if (StringUtils.isNotEmpty(value)) {
            in(column, StringUtils.splitWorker(value, ",", -1, false));
        }
        return this;
    }
 
    
    public Wrapper<T> notIn(String column, String value) {
        if (StringUtils.isNotEmpty(value)) {
            notIn(column, StringUtils.splitWorker(value, ",", -1, false));
        }
        return this;
    }
 
    
    public Wrapper<T> in(String column, Collection<?> value) {
        if (CollectionUtils.isNotEmpty(value))
            sql.WHERE(formatSql(inExpression(column, value, false), value.toArray()));
        return this;
    }
 
    
    public Wrapper<T> notIn(String column, Collection<?> value) {
        if (CollectionUtils.isNotEmpty(value))
            sql.WHERE(formatSql(inExpression(column, value, true), value.toArray()));
        return this;
    }
 
    
    public Wrapper<T> in(String column, Object[] value) {
        if (ArrayUtils.isNotEmpty(value))
            sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), false), value));
        return this;
    }
 
    
    public Wrapper<T> notIn(String column, Object... value) {
        if (ArrayUtils.isNotEmpty(value))
            sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), true), value));
        return this;
    }
 
    
    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;
    }
 
    
    public Wrapper<T> between(String column, Object val1, Object val2) {
        sql.WHERE(formatSql(String.format("%s BETWEEN {0} AND {1}", column), val1, val2));
        return this;
    }
 
    
    public Wrapper<T> notBetween(String column, Object val1, Object val2) {
        sql.WHERE(formatSql(String.format("%s NOT BETWEEN {0} AND {1}", column), val1, val2));
        return this;
    }
 
    
    public Wrapper<T> addFilter(String sqlWhere, Object... params) {
        return and(sqlWhere, params);
    }
 
    
    public Wrapper<T> addFilterIfNeed(boolean need, String sqlWhere, Object... params) {
        return need ? where(sqlWhere, params) : this;
    }
 
    
    protected String stripSqlInjection(String value) {
        return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
    }
 
    
    protected String formatSql(String sqlStr, Object... params) {
        return formatSqlIfNeed(true, sqlStr, params);
    }
 
    
    protected String formatSqlIfNeed(boolean need, String sqlStr, Object... params) {
        if (!need || StringUtils.isEmpty(sqlStr)) {
            return null;
        }
        // #200
        if (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;
    }
 
    
    public Wrapper<T> isWhere(Boolean bool) {
        this.isWhere = bool;
        return this;
    }
 
    
    public Wrapper<T> limit(int begin, int end) {
        sql.LIMIT(begin, end);
        return this;
    }
 
    
    public Map<String, Object> getParamNameValuePairs() {
        return paramNameValuePairs;
    }
 
    public String getParamAlias() {
        return StringUtils.isEmpty(paramAlias) ? DEFAULT_PARAM_ALIAS : paramAlias;
    }
 
    
    public Wrapper<T> 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;
    }
}

最后说一句,阅读源码,你会收获很多,看到别人的处理方式,你会有很大进步的。哈哈,今天你学到了吗

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

阅读原文内容投诉

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

软考中级精品资料免费领

  • 历年真题答案解析
  • 备考技巧名师总结
  • 高频考点精准押题
  • 2024年上半年信息系统项目管理师第二批次真题及答案解析(完整版)

    难度     813人已做
    查看
  • 【考后总结】2024年5月26日信息系统项目管理师第2批次考情分析

    难度     354人已做
    查看
  • 【考后总结】2024年5月25日信息系统项目管理师第1批次考情分析

    难度     318人已做
    查看
  • 2024年上半年软考高项第一、二批次真题考点汇总(完整版)

    难度     435人已做
    查看
  • 2024年上半年系统架构设计师考试综合知识真题

    难度     224人已做
    查看

相关文章

发现更多好内容

猜你喜欢

AI推送时光机
位置:首页-资讯-后端开发
咦!没有更多了?去看看其它编程学习网 内容吧
首页课程
资料下载
问答资讯