MP實戰系列(五)之封裝方法講解


mybatis plus封裝的方法怎么用?以及它們對應的sql是那些sql?及其什么情況用?

這些需要說下,以下我將會將我常用的說下,不是常用的,可能提以下或者不提。

根據主鍵查詢

    UserEntity userEntity = ud.selectById(id);

 

上述這個沒什么好說的

 

根據實體查詢

     UserEntity u = new UserEntity();
        u.setEmail("123@qq.com");
        UserEntity u1 = ud.selectOne(u);

這個就比較常用了,根據實體屬性查詢,在junit單元測試,調用dao,只能通過實體,如果是通過service,有個也可以使用,當然實體也同樣適用,在service中我經常用這個,

        
        EntityWrapper<UserEntity> wrapper = new EntityWrapper<UserEntity>();
        wrapper.eq("email", "123@qq.com");
        UserEntity u2 = userService.selectOne(wrapper);

EntityWrapper是個很強大的玩意,支持多條件查詢,例如下面:

wrapper.between(column, val1, val2)
        wrapper.groupBy(columns)  //對應sql中分組
        wrapper.eq(column, params) //相當於where條件
        wrapper.in(column, value) //sql中in
        wrapper.notIn(column, value) //sql中 not in
        wrapper.orderBy(columns, isAsc) //排序
        wrapper.exists(value) //相對於sql中exists查詢
        wrapper.notExists(value) //相當於sql中not exists查詢
        wrapper.notBetween(column, val1, val2) //相當於sql中在某個范圍內使用的between
        wrapper.ge(column, params) //大於等於
        wrapper.le(column, params) //小於等於
        wrapper.like(column, value) //模糊查詢
        wrapper.having(sqlHaving, params) //條件過濾

當然還有很多,其中wrapper有一個叫wrapper.setSqlSelect(column)的方法,這個方法主要用於sql優化,指定你需要的查詢字段。

 

                List<UserEntity> list = ud.selectByMap(columnMap) //通過map查詢 適用場景是分頁查詢
                List<UserEntity> list2 = ud.selectList(wrapper); //如果為Null,默認查詢所有
                List<UserEntity> list3 = ud.selectCount(wrapper) //通過EntityWrapper根據某個字段獲取總數
                List<UserEntity> list4 = ud.selectMaps(wrapper) //EntityWrapper查詢
                List<UserEntity> list5 = ud.selectPage(rowBounds, wrapper) //rowBounds里面封裝了起止和長度,wrapper具體條件
    

上面參數中例如columnMap是通過HashMap或者Map使字段以鍵值對的形式存在,然后進行查詢

分頁查詢更是簡單,因為RowBounds基本封裝好了索引和長度,wrapper就是前面提到的EntityWrapper

下面再貼貼EntityWrapper的源碼:

/**
 * Copyright (c) 2011-2014, hubin (jobob@qq.com).
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 com.baomidou.mybatisplus.toolkit.StringUtils;

/**
 * <p>
 * Entity 對象封裝操作類,定義T-SQL語法
 * </p>
 *
 * @author hubin , yanghu , Dyang , Caratacus
 * @Date 2016-11-7
 */
@SuppressWarnings("serial")
public class EntityWrapper<T> extends Wrapper<T> {

    /**
     * 數據庫表映射實體類
     */
    protected T entity = null;

    public EntityWrapper() {
        /* 注意,傳入查詢參數 */
    }

    public EntityWrapper(T entity) {
        this.entity = entity;
    }

    public EntityWrapper(T entity, String sqlSelect) {
        this.entity = entity;
        this.sqlSelect = sqlSelect;
    }

    @Override
    public T getEntity() {
        return entity;
    }

    public void setEntity(T entity) {
        this.entity = entity;
    }

    /**
     * SQL 片段
     */
    @Override
    public String getSqlSegment() {
        /*
         * 無條件
         */
        String sqlWhere = sql.toString();
        if (StringUtils.isEmpty(sqlWhere)) {
            return null;
        }

        /*
         * 根據當前實體判斷是否需要將WHERE替換成 AND 增加實體不為空但所有屬性為空的情況
         */
        return isWhere != null ? (isWhere ? sqlWhere : sqlWhere.replaceFirst("WHERE", AND_OR)) : sqlWhere.replaceFirst("WHERE", AND_OR);
    }

}

 

Wrapper源碼:

/**
 * Copyright (c) 2011-2014, hubin (jobob@qq.com).
 * <p>
 * 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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.entity.Column;
import com.baomidou.mybatisplus.entity.Columns;
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;


/**
 * <p>
 * 條件構造抽象類,定義T-SQL語法
 * </p>
 *
 * @author hubin , yanghu , Dyang , Caratacus
 * @Date 2016-11-7
 */
@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";
    /**
     * 實現了TSQL語法的SQL實體
     */
    protected final SqlPlus sql = new SqlPlus();
    private final Map<String, Object> paramNameValuePairs = new HashMap<>();
    private final AtomicInteger paramNameSeq = new AtomicInteger(0);
    protected String paramAlias = null;
    /**
     * SQL 查詢字段內容,例如:id,name,age
     */
    protected String sqlSelect = null;
    /**
     * 自定義是否輸出sql為 WHERE OR AND OR OR
     */
    protected Boolean isWhere;
    /**
     * 拼接WHERE后應該是AND還是ORnull
     */
    protected String AND_OR = "AND";

    /**
     * <p>
     * 兼容EntityWrapper
     * </p>
     *
     * @return
     */
    public T getEntity() {
        return null;
    }

    /**
     * 查看where構造是否為空
     *
     * @return
     */
    public boolean isEmptyOfWhere() {
        return sql.isEmptyOfWhere();
    }

    /**
     * 查看where構造是否不為空
     *
     * @return
     */
    public boolean isNotEmptyOfWhere() {
        return !isEmptyOfWhere();
    }

    public String getSqlSelect() {
        return StringUtils.isEmpty(sqlSelect) ? null : stripSqlInjection(sqlSelect);
    }

    public Wrapper<T> setSqlSelect(String sqlSelect) {
        if (StringUtils.isNotEmpty(sqlSelect)) {
            this.sqlSelect = sqlSelect;
        }
        return this;
    }

    /**
     * <p>
     * 使用字符串數組封裝sqlSelect,便於在不需要指定 AS 的情況下通過實體類自動生成的列靜態字段快速組裝 sqlSelect,<br/>
     * 減少手動錄入的錯誤率
     * </p>
     *
     * @param columns 字段
     * @return
     */
    public Wrapper<T> setSqlSelect(String... columns) {
        StringBuilder builder = new StringBuilder();
        for (String column : columns) {
            if (StringUtils.isNotEmpty(column)) {
                if (builder.length() > 0) {
                    builder.append(",");
                }
                builder.append(column);
            }
        }
        this.sqlSelect = builder.toString();
        return this;
    }

    /**
     * <p>
     * 使用對象封裝的setsqlselect
     * </p>
     *
     * @param column 字段
     * @return
     */
    public Wrapper<T> setSqlSelect(Column... column) {
        if (ArrayUtils.isNotEmpty(column)) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < column.length; i++) {
                if (column[i] != null) {
                    String col = column[i].getColumn();
                    String as = column[i].getAs();
                    if (StringUtils.isEmpty(col)) {
                        continue;
                    }
                    builder.append(col).append(as);
                    if (i < column.length - 1) {
                        builder.append(",");
                    }
                }
            }
            this.sqlSelect = builder.toString();
        }
        return this;
    }

    /**
     * <p>
     * 使用對象封裝的setsqlselect
     * </p>
     *
     * @param columns 字段
     * @return
     */
    public Wrapper<T> setSqlSelect(Columns columns) {
        Column[] columnArray = columns.getColumns();
        if (ArrayUtils.isNotEmpty(columnArray)) {
            setSqlSelect(columnArray);
        }
        return this;
    }

    /**
     * <p>
     * SQL 片段 (子類實現)
     * </p>
     */
    public abstract String getSqlSegment();

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder("Wrapper<T>:");
        String sqlSegment = getSqlSegment();
        sb.append(replacePlaceholder(sqlSegment));
        Object entity = getEntity();
        if (entity != null) {
            sb.append("\n");
            sb.append("entity=").append(entity.toString());
        }
        return sb.toString();
    }

    /**
     * <p>
     * 替換占位符
     * </p>
     *
     * @param sqlSegment
     * @return
     */
    private String replacePlaceholder(String sqlSegment) {
        if (StringUtils.isEmpty(sqlSegment)) {
            return StringUtils.EMPTY;
        }
        return sqlSegment.replaceAll("#\\{" + getParamAlias() + ".paramNameValuePairs.MPGENVAL[0-9]+}", "\\?");
    }

    /**
     * <p>
     * 原生占位符sql
     * </p>
     *
     * @return
     */
    public String originalSql() {
        return replacePlaceholder(getSqlSegment());
    }

    /**
     * <p>
     * SQL中WHERE關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").where(id!=null, "id={0}", id);
     * <p>
     * 輸出:<br>
     * 如果id=123:  WHERE (NAME='zhangsan' AND id=123)<br>
     * 如果id=null: WHERE (NAME='zhangsan')
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlWhere  where語句
     * @param params    參數集
     * @return this
     */
    public Wrapper<T> where(boolean condition, String sqlWhere, Object... params) {
        if (condition) {
            sql.WHERE(formatSql(sqlWhere, params));
        }
        return this;
    }

    /**
     * <p>
     * SQL中WHERE關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").where("id={0}","123");
     * <p>
     * 輸出: WHERE (NAME='zhangsan' AND id=123)
     * </p>
     *
     * @param sqlWhere where語句
     * @param params   參數集
     * @return this
     */
    public Wrapper<T> where(String sqlWhere, Object... params) {
        return where(true, sqlWhere, params);
    }

    /**
     * <p>
     * 等同於SQL的"field=value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> eq(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s = {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field=value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> eq(String column, Object params) {
        return eq(true, column, params);
    }

    /**
     * <p>
     * 等同於SQL的"field <> value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> ne(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s <> {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field <> value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> ne(String column, Object params) {
        return ne(true, column, params);

    }

    /**
     * <p>
     * 等同於SQL的"field=value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param params
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public Wrapper<T> allEq(boolean condition, Map<String, Object> params) {
        if (condition && 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;
    }

    /**
     * <p>
     * 等同於SQL的"field=value"表達式
     * </p>
     *
     * @param params
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public Wrapper<T> allEq(Map<String, Object> params) {
        return allEq(true, params);
    }

    /**
     * <p>
     * 等同於SQL的"field>value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> gt(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s > {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field>value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> gt(String column, Object params) {
        return gt(true, column, params);
    }

    /**
     * <p>
     * 等同於SQL的"field>=value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> ge(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s >= {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field>=value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> ge(String column, Object params) {
        return ge(true, column, params);
    }

    /**
     * <p>
     * 等同於SQL的"field<value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> lt(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s < {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field<value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> lt(String column, Object params) {
        return lt(true, column, params);
    }

    /**
     * <p>
     * 等同於SQL的"field<=value"表達式
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> le(boolean condition, String column, Object params) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s <= {0}", column), params));
        }
        return this;
    }

    /**
     * <p>
     * 等同於SQL的"field<=value"表達式
     * </p>
     *
     * @param column
     * @param params
     * @return
     */
    public Wrapper<T> le(String column, Object params) {
        return le(true, column, params);
    }

    /**
     * <p>
     * AND 連接后續條件
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlAnd    and條件語句
     * @param params    參數集
     * @return this
     */
    public Wrapper<T> and(boolean condition, String sqlAnd, Object... params) {
        if (condition) {
            sql.AND().WHERE(formatSql(sqlAnd, params));
        }
        return this;
    }

    /**
     * <p>
     * AND 連接后續條件
     * </p>
     *
     * @param sqlAnd and條件語句
     * @param params 參數集
     * @return this
     */
    public Wrapper<T> and(String sqlAnd, Object... params) {
        return and(true, sqlAnd, params);
    }

    /**
     * <p>
     * 使用AND連接並換行
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").andNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) AND (statu=1)
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlAnd    AND 條件語句
     * @param params    參數值
     * @return this
     */
    public Wrapper<T> andNew(boolean condition, String sqlAnd, Object... params) {
        if (condition) {
            sql.AND_NEW().WHERE(formatSql(sqlAnd, params));
        }
        return this;
    }

    /**
     * <p>
     * 使用AND連接並換行
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").andNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) AND (statu=1)
     * </p>
     *
     * @return this
     */
    public Wrapper<T> andNew() {
        sql.AND_NEW();
        return this;
    }

    /**
     * <p>
     * 使用AND連接並換行
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").andNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) AND (statu=1)
     * </p>
     *
     * @param sqlAnd AND 條件語句
     * @param params 參數值
     * @return this
     */
    public Wrapper<T> andNew(String sqlAnd, Object... params) {
        return andNew(true, sqlAnd, params);
    }

    /**
     * <p>
     * 使用AND連接並換行
     * </p>
     * <p>
     *
     * @return this
     */
    public Wrapper<T> and() {
        sql.AND();
        return this;
    }

    /**
     * <p>
     * 使用OR連接並換行
     * </p>
     *
     * @return this
     */
    public Wrapper<T> or() {
        sql.OR();
        return this;
    }

    /**
     * <p>
     * 添加OR條件
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlOr     or 條件語句
     * @param params    參數集
     * @return this
     */
    public Wrapper<T> or(boolean condition, String sqlOr, Object... params) {
        if (condition) {
            if (StringUtils.isEmpty(sql.toString())) {
                AND_OR = "OR";
            }
            sql.OR().WHERE(formatSql(sqlOr, params));
        }
        return this;
    }

    /**
     * <p>
     * 添加OR條件
     * </p>
     *
     * @param sqlOr  or 條件語句
     * @param params 參數集
     * @return this
     */
    public Wrapper<T> or(String sqlOr, Object... params) {
        return or(true, sqlOr, params);
    }

    /**
     * <p>
     * 使用OR換行,並添加一個帶()的新的條件
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").orNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) OR (statu=1)
     * </p>
     *
     * @return this
     */
    public Wrapper<T> orNew() {
        sql.OR_NEW();
        return this;
    }

    /**
     * <p>
     * 使用OR換行,並添加一個帶()的新的條件
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").orNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) OR (statu=1)
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlOr     AND 條件語句
     * @param params    參數值
     * @return this
     */
    public Wrapper<T> orNew(boolean condition, String sqlOr, Object... params) {
        if (condition) {
            if (StringUtils.isEmpty(sql.toString())) {
                AND_OR = "OR";
            }
            sql.OR_NEW().WHERE(formatSql(sqlOr, params));
        }
        return this;
    }

    /**
     * <p>
     * 使用OR換行,並添加一個帶()的新的條件
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").and("id=11").orNew("statu=1"); 輸出: WHERE
     * (name='zhangsan' AND id=11) OR (statu=1)
     * </p>
     *
     * @param sqlOr  AND 條件語句
     * @param params 參數值
     * @return this
     */
    public Wrapper<T> orNew(String sqlOr, Object... params) {
        return orNew(true, sqlOr, params);
    }

    /**
     * <p>
     * SQL中groupBy關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").groupBy("id,name")
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   SQL 中的 Group by 語句,無需輸入 Group By 關鍵字
     * @return this
     */
    public Wrapper<T> groupBy(boolean condition, String columns) {
        if (condition) {
            sql.GROUP_BY(columns);
        }
        return this;
    }

    /**
     * <p>
     * SQL中groupBy關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.where("name='zhangsan'").groupBy("id,name")
     * </p>
     *
     * @param columns SQL 中的 Group by 語句,無需輸入 Group By 關鍵字
     * @return this
     */
    public Wrapper<T> groupBy(String columns) {
        return groupBy(true, columns);
    }

    /**
     * <p>
     * SQL中having關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null")
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param sqlHaving having關鍵字后面跟隨的語句
     * @param params    參數集
     * @return EntityWrapper<T>
     */
    public Wrapper<T> having(boolean condition, String sqlHaving, Object... params) {
        if (condition) {
            sql.HAVING(formatSql(sqlHaving, params));
        }
        return this;
    }

    /**
     * <p>
     * SQL中having關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null")
     * </p>
     *
     * @param sqlHaving having關鍵字后面跟隨的語句
     * @param params    參數集
     * @return EntityWrapper<T>
     */
    public Wrapper<T> having(String sqlHaving, Object... params) {
        return having(true, sqlHaving, params);
    }

    /**
     * <p>
     * SQL中orderby關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null"
     * ).orderBy("id,name")
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   SQL 中的 order by 語句,無需輸入 Order By 關鍵字
     * @return this
     */
    public Wrapper<T> orderBy(boolean condition, String columns) {
        if (condition) {
            sql.ORDER_BY(columns);
        }
        return this;
    }

    /**
     * <p>
     * SQL中orderby關鍵字跟的條件語句
     * </p>
     * <p>
     * eg: ew.groupBy("id,name").having("id={0}",22).and("password is not null"
     * ).orderBy("id,name")
     * </p>
     *
     * @param columns SQL 中的 order by 語句,無需輸入 Order By 關鍵字
     * @return this
     */
    public Wrapper<T> orderBy(String columns) {
        return orderBy(true, columns);
    }

    /**
     * <p>
     * SQL中orderby關鍵字跟的條件語句,可根據變更動態排序
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   SQL 中的 order by 語句,無需輸入 Order By 關鍵字
     * @param isAsc     是否為升序
     * @return this
     */
    public Wrapper<T> orderBy(boolean condition, String columns, boolean isAsc) {
        if (condition && StringUtils.isNotEmpty(columns)) {
            sql.ORDER_BY(columns + (isAsc ? " ASC" : " DESC"));
        }
        return this;
    }

    /**
     * <p>
     * SQL中orderby關鍵字跟的條件語句,可根據變更動態排序
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   SQL 中的 order by 語句,無需輸入 Order By 關鍵字
     * @param isAsc     是否為升序
     * @return this
     */
    public Wrapper<T> orderBy(boolean condition, Collection<String> columns, boolean isAsc) {
        if (condition && CollectionUtils.isNotEmpty(columns)) {
            for (String column : columns) {
                orderBy(condition, column, isAsc);
            }
        }
        return this;
    }

    /**
     * <p>
     * SQL中orderby關鍵字跟的條件語句,可根據變更動態排序
     * </p>
     *
     * @param columns SQL 中的 order by 語句,無需輸入 Order By 關鍵字
     * @param isAsc   是否為升序
     * @return this
     */
    public Wrapper<T> orderBy(String columns, boolean isAsc) {
        return orderBy(true, columns, isAsc);
    }

    /**
     * <p>
     * 批量根據ASC排序
     * </p>
     *
     * @param columns 需要排序的集合
     * @return this
     */
    public Wrapper<T> orderAsc(Collection<String> columns) {
        return orderBy(true, columns, true);
    }

    /**
     * <p>
     * 批量根據DESC排序
     * </p>
     *
     * @param columns 需要排序的集合
     * @return this
     */
    public Wrapper<T> orderDesc(Collection<String> columns) {
        return orderBy(true, columns, false);
    }

    /**
     * <p>
     * LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值
     * @return this
     */
    public Wrapper<T> like(boolean condition, String column, String value) {
        if (condition) {
            handerLike(column, value, SqlLike.DEFAULT, false);
        }
        return this;
    }

    /**
     * <p>
     * LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值
     * @return this
     */
    public Wrapper<T> like(String column, String value) {
        return like(true, column, value);
    }

    /**
     * <p>
     * NOT LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值
     * @return this
     */
    public Wrapper<T> notLike(boolean condition, String column, String value) {
        if (condition) {
            handerLike(column, value, SqlLike.DEFAULT, true);
        }
        return this;
    }

    /**
     * <p>
     * NOT LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值
     * @return this
     */
    public Wrapper<T> notLike(String column, String value) {
        return notLike(true, column, value);
    }

    /**
     * <p>
     * 處理LIKE操作
     * </p>
     *
     * @param column 字段名稱
     * @param value  like匹配值
     * @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)));
        }
    }

    /**
     * <p>
     * LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值
     * @param type
     * @return this
     */
    public Wrapper<T> like(boolean condition, String column, String value, SqlLike type) {
        if (condition) {
            handerLike(column, value, type, false);
        }
        return this;
    }

    /**
     * <p>
     * LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值
     * @param type
     * @return this
     */
    public Wrapper<T> like(String column, String value, SqlLike type) {
        return like(true, column, value, type);
    }

    /**
     * <p>
     * NOT LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值
     * @param type
     * @return this
     */
    public Wrapper<T> notLike(boolean condition, String column, String value, SqlLike type) {
        if (condition) {
            handerLike(column, value, type, true);
        }
        return this;
    }

    /**
     * <p>
     * NOT LIKE條件語句,value中無需前后%
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值
     * @param type
     * @return this
     */
    public Wrapper<T> notLike(String column, String value, SqlLike type) {
        return notLike(true, column, value, type);
    }

    /**
     * <p>
     * is not null 條件
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   字段名稱。多個字段以逗號分隔。
     * @return this
     */
    public Wrapper<T> isNotNull(boolean condition, String columns) {
        if (condition) {
            sql.IS_NOT_NULL(columns);
        }
        return this;
    }

    /**
     * <p>
     * is not null 條件
     * </p>
     *
     * @param columns 字段名稱。多個字段以逗號分隔。
     * @return this
     */
    public Wrapper<T> isNotNull(String columns) {
        return isNotNull(true, columns);
    }

    /**
     * <p>
     * is null 條件
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param columns   字段名稱。多個字段以逗號分隔。
     * @return this
     */
    public Wrapper<T> isNull(boolean condition, String columns) {
        if (condition) {
            sql.IS_NULL(columns);
        }
        return this;
    }

    /**
     * <p>
     * is null 條件
     * </p>
     *
     * @param columns 字段名稱。多個字段以逗號分隔。
     * @return this
     */
    public Wrapper<T> isNull(String columns) {
        return isNull(true, columns);
    }

    /**
     * <p>
     * EXISTS 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param value     匹配值
     * @return this
     */
    public Wrapper<T> exists(boolean condition, String value) {
        if (condition) {
            sql.EXISTS(value);
        }
        return this;
    }

    /**
     * <p>
     * EXISTS 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param value 匹配值
     * @return this
     */
    public Wrapper<T> exists(String value) {
        return exists(true, value);
    }

    /**
     * <p>
     * NOT EXISTS條件語句
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param value     匹配值
     * @return this
     */
    public Wrapper<T> notExists(boolean condition, String value) {
        if (condition) {
            sql.NOT_EXISTS(value);
        }
        return this;
    }

    /**
     * <p>
     * NOT EXISTS條件語句
     * </p>
     *
     * @param value 匹配值
     * @return this
     */
    public Wrapper<T> notExists(String value) {
        return notExists(true, value);
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     逗號拼接的字符串
     * @return this
     */
    public Wrapper<T> in(boolean condition, String column, String value) {
        if (condition && StringUtils.isNotEmpty(value)) {
            in(column, StringUtils.splitWorker(value, ",", -1, false));
        }
        return this;
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param column 字段名稱
     * @param value  逗號拼接的字符串
     * @return this
     */
    public Wrapper<T> in(String column, String value) {
        return in(true, column, value);
    }

    /**
     * <p>
     * NOT IN條件語句
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     逗號拼接的字符串
     * @return this
     */
    public Wrapper<T> notIn(boolean condition, String column, String value) {
        if (condition && StringUtils.isNotEmpty(value)) {
            notIn(column, StringUtils.splitWorker(value, ",", -1, false));
        }
        return this;
    }

    /**
     * <p>
     * NOT IN條件語句
     * </p>
     *
     * @param column 字段名稱
     * @param value  逗號拼接的字符串
     * @return this
     */
    public Wrapper<T> notIn(String column, String value) {
        return notIn(true, column, value);
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值 集合
     * @return this
     */
    public Wrapper<T> in(boolean condition, String column, Collection<?> value) {
        if (condition && CollectionUtils.isNotEmpty(value)) {
            sql.WHERE(formatSql(inExpression(column, value, false), value.toArray()));
        }
        return this;
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值 集合
     * @return this
     */
    public Wrapper<T> in(String column, Collection<?> value) {
        return in(true, column, value);
    }

    /**
     * <p>
     * NOT IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值 集合
     * @return this
     */
    public Wrapper<T> notIn(boolean condition, String column, Collection<?> value) {
        if (condition && CollectionUtils.isNotEmpty(value)) {
            sql.WHERE(formatSql(inExpression(column, value, true), value.toArray()));
        }
        return this;
    }

    /**
     * <p>
     * NOT IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值 集合
     * @return this
     */
    public Wrapper<T> notIn(String column, Collection<?> value) {
        return notIn(true, column, value);
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值 object數組
     * @return this
     */
    public Wrapper<T> in(boolean condition, String column, Object[] value) {
        if (condition && ArrayUtils.isNotEmpty(value)) {
            sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), false), value));
        }
        return this;
    }

    /**
     * <p>
     * IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值 object數組
     * @return this
     */
    public Wrapper<T> in(String column, Object[] value) {
        return in(true, column, value);
    }

    /**
     * <p>
     * NOT IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param value     匹配值 object數組
     * @return this
     */
    public Wrapper<T> notIn(boolean condition, String column, Object... value) {
        if (condition && ArrayUtils.isNotEmpty(value)) {
            sql.WHERE(formatSql(inExpression(column, Arrays.asList(value), true), value));
        }
        return this;
    }

    /**
     * <p>
     * NOT IN 條件語句,目前適配mysql及oracle
     * </p>
     *
     * @param column 字段名稱
     * @param value  匹配值 object數組
     * @return this
     */
    public Wrapper<T> notIn(String column, Object... value) {
        return notIn(true, column, value);
    }

    /**
     * <p>
     * 獲取in表達式
     * </p>
     *
     * @param column 字段名稱
     * @param value  集合
     * @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;
    }

    /**
     * <p>
     * betwwee 條件語句
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param val1
     * @param val2
     * @return this
     */
    public Wrapper<T> between(boolean condition, String column, Object val1, Object val2) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s BETWEEN {0} AND {1}", column), val1, val2));
        }
        return this;
    }

    /**
     * <p>
     * betwwee 條件語句
     * </p>
     *
     * @param column 字段名稱
     * @param val1
     * @param val2
     * @return this
     */
    public Wrapper<T> between(String column, Object val1, Object val2) {
        return between(true, column, val1, val2);
    }

    /**
     * <p>
     * NOT betwwee 條件語句
     * </p>
     *
     * @param condition 拼接的前置條件
     * @param column    字段名稱
     * @param val1
     * @param val2
     * @return this
     */
    public Wrapper<T> notBetween(boolean condition, String column, Object val1, Object val2) {
        if (condition) {
            sql.WHERE(formatSql(String.format("%s NOT BETWEEN {0} AND {1}", column), val1, val2));
        }
        return this;
    }

    /**
     * <p>
     * NOT betwwee 條件語句
     * </p>
     *
     * @param column 字段名稱
     * @param val1
     * @param val2
     * @return this
     */
    public Wrapper<T> notBetween(String column, Object val1, Object val2) {
        return notBetween(true, column, val1, val2);

    }

    /**
     * <p>
     * 為了兼容之前的版本,可使用where()或and()替代
     * </p>
     *
     * @param sqlWhere where sql部分
     * @param params   參數集
     * @return this
     */
    public Wrapper<T> addFilter(String sqlWhere, Object... params) {
        return and(sqlWhere, params);
    }

    /**
     * <p>
     * 根據判斷條件來添加條件語句部分 使用 andIf() 替代
     * </p>
     * <p>
     * eg: ew.filterIfNeed(false,"name='zhangsan'").where("name='zhangsan'")
     * .filterIfNeed(true,"id={0}",22)
     * <p>
     * 輸出: WHERE (name='zhangsan' AND id=22)
     * </p>
     *
     * @param need     是否需要添加該條件
     * @param sqlWhere 條件語句
     * @param params   參數集
     * @return this
     */
    public Wrapper<T> addFilterIfNeed(boolean need, String sqlWhere, Object... params) {
        return need ? where(sqlWhere, params) : this;
    }

    /**
     * <p>
     * SQL注入內容剝離
     * </p>
     *
     * @param value 待處理內容
     * @return this
     */
    protected String stripSqlInjection(String value) {
        return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
    }

    /**
     * <p>
     * 格式化SQL
     * </p>
     *
     * @param sqlStr SQL語句部分
     * @param params 參數集
     * @return this
     */
    protected String formatSql(String sqlStr, Object... params) {
        return formatSqlIfNeed(true, sqlStr, params);
    }

    /**
     * <p>
     * 根據需要格式化SQL<BR>
     * <BR>
     * Format SQL for methods: EntityWrapper<T>.where/and/or...("name={0}", value);
     * ALL the {<b>i</b>} will be replaced with #{MPGENVAL<b>i</b>}<BR>
     * <BR>
     * ew.where("sample_name=<b>{0}</b>", "haha").and("sample_age &gt;<b>{0}</b>
     * and sample_age&lt;<b>{1}</b>", 18, 30) <b>TO</b>
     * sample_name=<b>#{MPGENVAL1}</b> and sample_age&gt;#<b>{MPGENVAL2}</b> and
     * sample_age&lt;<b>#{MPGENVAL3}</b><BR>
     * </p>
     *
     * @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;
        }
        // #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;
    }

    /**
     * <p>
     * 自定義是否輸出sql開頭為 `WHERE` OR `AND` OR `OR`
     * </p>
     *
     * @param bool
     * @return this
     */
    public Wrapper<T> isWhere(Boolean bool) {
        this.isWhere = bool;
        return this;
    }

    /**
     * <p>
     * 手動把sql拼接到最后(有sql注入的風險,請謹慎使用)
     * </p>
     *
     * @param limit
     * @return this
     */
    public Wrapper<T> last(String limit) {
        sql.LAST(limit);
        return this;
    }

    /**
     * Fix issue 200.
     *
     * @return
     * @since 2.0.3
     */
    public Map<String, Object> getParamNameValuePairs() {
        return paramNameValuePairs;
    }

    public String getParamAlias() {
        return StringUtils.isEmpty(paramAlias) ? DEFAULT_PARAM_ALIAS : paramAlias;
    }

    /**
     * <p>
     * 參數別名設置,初始化時優先設置該值、重復設置異常
     * </p>
     *
     * @param paramAlias 參數別名
     * @return
     */
    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;
    }
}

 

通過看源碼更好的了解它

接下來再提提增刪改:

         ud.insert(entity)  //應用場景是指定你需要的實體增加到對應的表中
         ud.delete(wrapper) //通過EntityWrapper指定字段刪除數據
         ud.deleteById(id)  //主鍵刪除
         ud.deleteByMap(columnMap) //通過map刪除
         ud.deleteBatchIds(idList) //批量刪除
         ud.insertAllColumn(entity) //默認插入該實體所有字段
         ud.insertUserEntity(map) //通過map新增數據
         ud.update(entity, wrapper) //通過EntityWrapper更新實體
         ud.updateAllColumnById(entity) //更新所有實體,通過主鍵更新
         ud.updateById(entity) //更新指定實體,通過主鍵更新
         ud.updateUserMap(map) //通過map更新

如果是在DAO中

例如:

UserEntity u = new UserEntity();
u.setName("test")
int lines = ud.insertEntity(u);

后面的用法諸如上述這樣的,如果是map就要以map的形式

 

 

通過這篇博文,可以讓你明白這些方法的應用場景

 


免責聲明!

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



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