广告
返回顶部
首页 > 资讯 > 后端开发 > Python >MyBatis-Plus工具使用之EntityWrapper解析
  • 468
分享到

MyBatis-Plus工具使用之EntityWrapper解析

2024-04-02 19:04:59 468人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

目录EntityWrapper使用解析EntityWrapper源码解读EntityWrapper使用解析 1、项目中引入jar包,我这里使用Maven构建 <dependen

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;
    }
}

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

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

--结束END--

本文标题: MyBatis-Plus工具使用之EntityWrapper解析

本文链接: https://www.lsjlt.com/news/143402.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作