浏览代码

1、修改EntityWrapper符合T-SQL语法标准的条件进行方法封装定义。
2、去掉Page中的asc与orderby,所有条件封装到EntityWrapper中。

yanghu 9 年之前
父节点
当前提交
92c33840c8

+ 93 - 97
mybatis-plus/src/main/java/com/baomidou/framework/service/impl/ServiceImpl.java

@@ -1,12 +1,12 @@
 /**
  * Copyright (c) 2011-2016, 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
@@ -29,104 +29,100 @@ import com.baomidou.mybatisplus.plugins.Page;
  * <p>
  * IService 实现类( 泛型:M 是 mapper 对象, T 是实体 , I 是主键泛型 )
  * </p>
- * 
+ *
  * @author hubin
  * @Date 2016-04-20
  */
 public class ServiceImpl<M extends BaseMapper<T, I>, T, I> implements IService<T, I> {
 
-	@Autowired
-	protected M baseMapper;
-
-	/**
-	 * 判断数据库操作是否成功
-	 * 
-	 * @param result
-	 *            数据库操作返回影响条数
-	 * @return boolean
-	 */
-	protected boolean retBool(int result) {
-		return (result >= 1) ? true : false;
-	}
-
-	public boolean insert(T entity) {
-		return retBool(baseMapper.insert(entity));
-	}
-
-	public boolean insertSelective(T entity) {
-		return retBool(baseMapper.insertSelective(entity));
-	}
-
-	public boolean insertBatch(List<T> entityList) {
-		return retBool(baseMapper.insertBatch(entityList));
-	}
-
-	public boolean deleteById(I id) {
-		return retBool(baseMapper.deleteById(id));
-	}
-
-	public boolean deleteByMap(Map<String, Object> columnMap) {
-		return retBool(baseMapper.deleteByMap(columnMap));
-	}
-
-	public boolean deleteSelective(T entity) {
-		return retBool(baseMapper.deleteSelective(entity));
-	}
-
-	public boolean deleteBatchIds(List<I> idList) {
-		return retBool(baseMapper.deleteBatchIds(idList));
-	}
-
-	public boolean updateById(T entity) {
-		return retBool(baseMapper.updateById(entity));
-	}
-
-	public boolean updateSelectiveById(T entity) {
-		return retBool(baseMapper.updateSelectiveById(entity));
-	}
-
-	public boolean update(T entity, T whereEntity) {
-		return retBool(baseMapper.update(entity, whereEntity));
-	}
-
-	public boolean updateSelective(T entity, T whereEntity) {
-		return retBool(baseMapper.updateSelective(entity, whereEntity));
-	}
-
-	public boolean updateBatchById(List<T> entityList) {
-		return retBool(baseMapper.updateBatchById(entityList));
-	}
-
-	public T selectById(I id) {
-		return baseMapper.selectById(id);
-	}
-
-	public List<T> selectBatchIds(List<I> idList) {
-		return baseMapper.selectBatchIds(idList);
-	}
-
-	public List<T> selectByMap(Map<String, Object> columnMap) {
-		return baseMapper.selectByMap(columnMap);
-	}
-
-	public T selectOne(T entity) {
-		return baseMapper.selectOne(entity);
-	}
-
-	public int selectCount(T entity) {
-		return baseMapper.selectCount(entity);
-	}
-
-	public List<T> selectList(EntityWrapper<T> entityWrapper) {
-		return baseMapper.selectList(entityWrapper);
-	}
-
-	public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) {
-		if (null != entityWrapper) {
-			entityWrapper.addFilter(" ORDER BY {0} {1}", page.getOrderByField(), page.isAsc() ? "" : "DESC");
-		}
-		page.setRecords(baseMapper.selectPage(page, entityWrapper));
-		return page;
-	}
+    @Autowired
+    protected M baseMapper;
+
+    /**
+     * 判断数据库操作是否成功
+     *
+     * @param result 数据库操作返回影响条数
+     * @return boolean
+     */
+    protected boolean retBool(int result) {
+        return result >= 1;
+    }
+
+    public boolean insert(T entity) {
+        return retBool(baseMapper.insert(entity));
+    }
+
+    public boolean insertSelective(T entity) {
+        return retBool(baseMapper.insertSelective(entity));
+    }
+
+    public boolean insertBatch(List<T> entityList) {
+        return retBool(baseMapper.insertBatch(entityList));
+    }
+
+    public boolean deleteById(I id) {
+        return retBool(baseMapper.deleteById(id));
+    }
+
+    public boolean deleteByMap(Map<String, Object> columnMap) {
+        return retBool(baseMapper.deleteByMap(columnMap));
+    }
+
+    public boolean deleteSelective(T entity) {
+        return retBool(baseMapper.deleteSelective(entity));
+    }
+
+    public boolean deleteBatchIds(List<I> idList) {
+        return retBool(baseMapper.deleteBatchIds(idList));
+    }
+
+    public boolean updateById(T entity) {
+        return retBool(baseMapper.updateById(entity));
+    }
+
+    public boolean updateSelectiveById(T entity) {
+        return retBool(baseMapper.updateSelectiveById(entity));
+    }
+
+    public boolean update(T entity, T whereEntity) {
+        return retBool(baseMapper.update(entity, whereEntity));
+    }
+
+    public boolean updateSelective(T entity, T whereEntity) {
+        return retBool(baseMapper.updateSelective(entity, whereEntity));
+    }
+
+    public boolean updateBatchById(List<T> entityList) {
+        return retBool(baseMapper.updateBatchById(entityList));
+    }
+
+    public T selectById(I id) {
+        return baseMapper.selectById(id);
+    }
+
+    public List<T> selectBatchIds(List<I> idList) {
+        return baseMapper.selectBatchIds(idList);
+    }
+
+    public List<T> selectByMap(Map<String, Object> columnMap) {
+        return baseMapper.selectByMap(columnMap);
+    }
+
+    public T selectOne(T entity) {
+        return baseMapper.selectOne(entity);
+    }
+
+    public int selectCount(T entity) {
+        return baseMapper.selectCount(entity);
+    }
+
+    public List<T> selectList(EntityWrapper<T> entityWrapper) {
+        return baseMapper.selectList(entityWrapper);
+    }
+
+    public Page<T> selectPage(Page<T> page, EntityWrapper<T> entityWrapper) {
+        page.setRecords(baseMapper.selectPage(page, entityWrapper));
+        return page;
+    }
 
 }

+ 286 - 148
mybatis-plus/src/main/java/com/baomidou/mybatisplus/mapper/EntityWrapper.java

@@ -1,12 +1,12 @@
 /**
  * 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
@@ -15,164 +15,302 @@
  */
 package com.baomidou.mybatisplus.mapper;
 
-import java.text.MessageFormat;
-
 import com.baomidou.mybatisplus.toolkit.StringUtils;
 
+import java.text.MessageFormat;
+
 /**
  * <p>
  * Entity 对象封装操作类
  * </p>
- * 
+ *
  * @author hubin
  * @Date 2016-03-15
  */
 public class EntityWrapper<T> {
 
-	/**
-	 * 数据库表映射实体类
-	 */
-	private T entity = null;
-
-	/**
-	 * SQL 查询字段内容,例如:id,name,age
-	 */
-	private String sqlSelect = null;
-
-	/**
-	 * 查询条件
-	 */
-	protected StringBuffer queryFilter = new StringBuffer();
-
-	public EntityWrapper() {
-		// to do nothing
-	}
-
-	public EntityWrapper(T entity) {
-		this.entity = entity;
-	}
-
-	public EntityWrapper(T entity, String sqlSelect) {
-		this.entity = entity;
-		this.sqlSelect = sqlSelect;
-	}
-
-	public T getEntity() {
-		return entity;
-	}
-
-	public void setEntity(T entity) {
-		this.entity = entity;
-	}
-
-	public String getSqlSelect() {
-		if (StringUtils.isEmpty(sqlSelect)) {
-			return null;
-		}
-		return stripSqlInjection(sqlSelect);
-	}
-
-	public void setSqlSelect(String sqlSelect) {
-		if (StringUtils.isNotEmpty(sqlSelect)) {
-			this.sqlSelect = sqlSelect;
-		}
-	}
-
-	/**
-	 * SQL 片段
-	 */
-	public String getSqlSegment() {
-		/*
-		 * 无条件
-		 */
-		String tempQuery = queryFilter.toString().trim();
-		if (StringUtils.isEmpty(tempQuery)) {
-			return null;
-		}
+    /**
+     * 定义T-SQL SELECT中的WHERE关键字
+     */
+    private final String WHERE_WORD = " WHERE ";
+    /**
+     * 定义T-SQL SELECT中的AND关键字
+     */
+    private final String AND_WORD = " AND ";
+    /**
+     * 定义T-SQL SELECT中的OR关键字
+     */
+    private final String OR_WORD = " OR ";
+    /**
+     * 定义T-SQL SELECT中的GROUP BY关键字
+     */
+    private final String GROUPBY_WORD = " GROUP BY ";
+    /**
+     * 定义T-SQL SELECT中的HAVING关键字
+     */
+    private final String HAVING_WORD = " HAVING ";
+    /**
+     * 定义T-SQL SELECT中的ORDER BY关键字
+     */
+    private final String ORDERBY_WORD = " ORDER BY ";
+    /**
+     * 定义T-SQL SELECT中的ORDER BY语句中排序的 DESC关键字
+     */
+    private final String DESC_WORD = " DESC ";
+    /**
+     * 定义T-SQL SELECT中的ORDER BY语句中排序的 ASC关键字
+     */
+    private final String ASC_WORD = " ASC ";
 
-		/*
-		 * 只排序、直接返回
-		 */
-		if (tempQuery.toUpperCase().indexOf("ORDER BY") == 0) {
-			return stripSqlInjection(queryFilter.toString());
-		}
+    /**
+     * 数据库表映射实体类
+     */
+    private T entity = null;
+
+    /**
+     * SQL 查询字段内容,例如:id,name,age
+     */
+    private String sqlSelect = null;
+
+    /**
+     * 查询条件
+     */
+    protected StringBuffer queryFilter = new StringBuffer();
+
+    public EntityWrapper() {
+        // to do nothing
+    }
+
+    public EntityWrapper(T entity) {
+        this.entity = entity;
+    }
+
+    public EntityWrapper(T entity, String sqlSelect) {
+        this.entity = entity;
+        this.sqlSelect = sqlSelect;
+    }
 
-		/*
-		 * SQL 片段
+    public T getEntity() {
+        return entity;
+    }
+
+    public void setEntity(T entity) {
+        this.entity = entity;
+    }
+
+    public String getSqlSelect() {
+        if (StringUtils.isEmpty(sqlSelect)) {
+            return null;
+        }
+        return stripSqlInjection(sqlSelect);
+    }
+
+    public void setSqlSelect(String sqlSelect) {
+        if (StringUtils.isNotEmpty(sqlSelect)) {
+            this.sqlSelect = sqlSelect;
+        }
+    }
+
+    /**
+     * SQL 片段
+     */
+    public String getSqlSegment() {
+        /*
+         * 无条件
 		 */
-		StringBuffer sqlSegment = new StringBuffer();
-		if (null == this.getEntity()) {
-			sqlSegment.append(" WHERE ");
-		} else {
-			sqlSegment.append(" AND ");
-		}
-		sqlSegment.append(queryFilter.toString());
-		return stripSqlInjection(sqlSegment.toString());
-	}
-
-	/**
-	 * <p>
-	 * 添加查询条件
-	 * </p>
-	 * <p>
-	 * 例如: ew.addFilter("name={0}", "'123'") <br>
-	 * 输出:name='123'
-	 * </p>
-	 * 
-	 * @param filter
-	 *            SQL 片段内容
-	 * @param params
-	 *            格式参数
-	 * @return
-	 */
-	public EntityWrapper<T> addFilter(String filter, Object... params) {
-		if (StringUtils.isEmpty(filter)) {
-			return this;
-		}
-		if (null != params && params.length >= 1) {
-			queryFilter.append(MessageFormat.format(filter, params));
-		} else {
-			queryFilter.append(filter);
-		}
-		return this;
-	}
-
-	/**
-	 * <p>
-	 * 添加查询条件
-	 * </p>
-	 * <p>
-	 * 例如: ew.addFilter("name={0}", "'123'").addFilterIfNeed(false,
-	 * " ORDER BY id") <br>
-	 * 输出:name='123'
-	 * </p>
-	 * 
-	 * @param willAppend
-	 *            判断条件 true 输出 SQL 片段,false 不输出
-	 * @param filter
-	 *            SQL 片段
-	 * @param params
-	 *            格式参数
-	 * @return
-	 */
-	public EntityWrapper<T> addFilterIfNeed(boolean willAppend, String filter, Object... params) {
-		if (willAppend) {
-			addFilter(filter, params);
-		}
-		return this;
-	}
-
-	/**
-	 * <p>
-	 * SQL注入内容剥离
-	 * </p>
-	 * 
-	 * @param value
-	 *            待处理内容
-	 * @return
-	 */
-	protected String stripSqlInjection(String value) {
-		return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
-	}
+        String tempQuery = queryFilter.toString().trim();
+        if (StringUtils.isEmpty(tempQuery)) {
+            return null;
+        }
+
+        // 使用防SQL注入处理后返回
+        return stripSqlInjection(queryFilter.toString());
+    }
+
+    /**
+     * <p>SQL中WHERE关键字跟的条件语句</p>
+     * <p>eg: ew.where("name='zhangsan'").and("id={0}",22).and("password is not null")</p>
+     *
+     * @param sqlWhere where语句
+     * @param params   参数集
+     * @return
+     */
+    public EntityWrapper<T> where(String sqlWhere, Object... params) {
+        addFilter(WHERE_WORD, sqlWhere, params);
+        return this;
+    }
+
+    /**
+     * <p>SQL中AND关键字跟的条件语句</p>
+     * <p>eg: ew.where("name='zhangsan'").and("id={0}",22).and("password is not null")</p>
+     *
+     * @param sqlAnd and连接串
+     * @param params 参数集
+     * @return
+     */
+    public EntityWrapper<T> and(String sqlAnd, Object... params) {
+        addFilter(AND_WORD, sqlAnd, params);
+        return this;
+    }
+
+    /**
+     * <p>与and方法的区别是 可根据需要判断是否添加该条件</p>
+     *
+     * @param need   是否需要使用该and条件
+     * @param sqlAnd and条件语句
+     * @param params 参数集
+     * @return
+     */
+    public EntityWrapper<T> andIfNeed(boolean need, String sqlAnd, Object... params) {
+        addFilterIfNeed(need, AND_WORD, sqlAnd, params);
+        return this;
+    }
+
+    /**
+     * <p>SQL中AND关键字跟的条件语句</p>
+     * <p>eg: ew.where("name='zhangsan'").or("password is not null")</p>
+     *
+     * @param sqlOr  or条件语句
+     * @param params 参数集
+     * @return
+     */
+    public EntityWrapper<T> or(String sqlOr, Object... params) {
+        addFilter(OR_WORD, sqlOr, params);
+        return this;
+    }
+
+    /**
+     * <p>与or方法的区别是 可根据需要判断是否添加该条件</p>
+     *
+     * @param need   是否需要使用OR条件
+     * @param sqlOr  OR条件语句
+     * @param params 参数集
+     * @return
+     */
+    public EntityWrapper<T> orIfNeed(boolean need, String sqlOr, Object... params) {
+        addFilterIfNeed(need, OR_WORD, sqlOr, params);
+        return this;
+    }
+
+    /**
+     * <p>SQL中groupBy关键字跟的条件语句</p>
+     * <p>eg: ew.where("name='zhangsan'").and("id={0}",22).and("password is not null")
+     * .groupBy("id,name")
+     * </p>
+     *
+     * @param sqlGroupBy sql中的Group by语句,无需输入Group By关键字
+     * @return this
+     */
+    public EntityWrapper<T> groupBy(String sqlGroupBy) {
+        addFilter(GROUPBY_WORD, sqlGroupBy);
+        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
+     */
+    public EntityWrapper<T> having(String sqlHaving, Object... params) {
+        addFilter(HAVING_WORD, sqlHaving, params);
+        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 sqlOrderBy sql中的order by语句,无需输入Order By关键字
+     * @return this
+     */
+    public EntityWrapper<T> orderBy(String sqlOrderBy) {
+        addFilter(ORDERBY_WORD, sqlOrderBy);
+        return this;
+    }
+
+    /**
+     * <p>SQL中orderby关键字跟的条件语句,可根据变更动态排序</p>
+     *
+     * @param sqlOrderBy
+     * @param isAsc
+     * @return
+     */
+    public EntityWrapper<T> orderBy(String sqlOrderBy, boolean isAsc) {
+        addFilter(ORDERBY_WORD, sqlOrderBy);
+        if (isAsc) {
+            queryFilter.append(ASC_WORD);
+        } else {
+            queryFilter.append(DESC_WORD);
+        }
+        return this;
+    }
+
+
+    /**
+     * <p>
+     * SQL注入内容剥离
+     * </p>
+     *
+     * @param value 待处理内容
+     * @return
+     */
+    protected String stripSqlInjection(String value) {
+        return value.replaceAll("('.+--)|(--)|(\\|)|(%7C)", "");
+    }
+
+    /**
+     * <p>
+     * 添加查询条件
+     * </p>
+     * <p>
+     * 例如: ew.addFilter("name={0}", "'123'") <br>
+     * 输出:name='123'
+     * </p>
+     *
+     * @param filter SQL 片段内容
+     * @param params 格式参数
+     * @return
+     */
+    private EntityWrapper<T> addFilter(String keyWord, String filter, Object... params) {
+        if (StringUtils.isEmpty(filter)) {
+            return this;
+        }
+        queryFilter.append(keyWord);
+        if (null != params && params.length >= 1) {
+            queryFilter.append(MessageFormat.format(filter, params));
+        } else {
+            queryFilter.append(filter);
+        }
+        return this;
+    }
+
+    /**
+     * <p>
+     * 添加查询条件
+     * </p>
+     * <p>
+     * 例如: ew.addFilter("name={0}", "'123'").addFilterIfNeed(false, " ORDER BY id") <br>
+     * 输出:name='123'
+     * </p>
+     *
+     * @param keyWord    SQL关键字
+     * @param willAppend 判断条件 true 输出 SQL 片段,false 不输出
+     * @param filter     SQL 片段
+     * @param params     格式参数
+     * @return
+     */
+    private EntityWrapper<T> addFilterIfNeed(boolean willAppend, String keyWord, String filter, Object... params) {
+        if (willAppend) {
+            addFilter(keyWord, filter, params);
+        }
+        return this;
+    }
 
 }

+ 40 - 80
mybatis-plus/src/main/java/com/baomidou/mybatisplus/plugins/Page.java

@@ -1,12 +1,12 @@
 /**
  * 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
@@ -15,93 +15,53 @@
  */
 package com.baomidou.mybatisplus.plugins;
 
+import com.baomidou.mybatisplus.plugins.pagination.Pagination;
+
 import java.util.Collections;
 import java.util.List;
 
-import com.baomidou.mybatisplus.plugins.pagination.Pagination;
-import com.baomidou.mybatisplus.toolkit.StringUtils;
-
 /**
  * <p>
  * 实现分页辅助类
  * </p>
- * 
+ *
  * @author hubin
  * @Date 2016-03-01
  */
 public class Page<T> extends Pagination {
 
-	private static final long serialVersionUID = 1L;
-
-	/**
-	 * 查询数据列表
-	 */
-	private List<T> records = Collections.emptyList();
-
-	/**
-	 * <p>
-	 * SQL 排序 ORDER BY 字段,例如: id DESC(根据id倒序查询)
-	 * </p>
-	 * <p>
-	 * DESC 表示按倒序排序(即:从大到小排序)<br>
-	 * ASC 表示按正序排序(即:从小到大排序)
-	 * </p>
-	 */
-	private String orderByField;
-
-	/**
-	 * 是否为升序 ASC( 默认: true )
-	 */
-	private boolean isAsc = true;
-
-	public Page() {
-		/* 注意,传入翻页参数 */
-	}
-
-	public Page(int current, int size) {
-		super(current, size);
-	}
-
-	public Page(int current, int size, String orderByField) {
-		super(current, size);
-		this.setOrderByField(orderByField);
-	}
-
-	public List<T> getRecords() {
-		return records;
-	}
-
-	public void setRecords(List<T> records) {
-		this.records = records;
-	}
-
-	public String getOrderByField() {
-		return orderByField;
-	}
-
-	public void setOrderByField(String orderByField) {
-		if (StringUtils.isNotEmpty(orderByField)) {
-			this.orderByField = orderByField;
-		}
-	}
-
-	public boolean isAsc() {
-		return isAsc;
-	}
-
-	public void setAsc(boolean isAsc) {
-		this.isAsc = isAsc;
-	}
-
-	@Override
-	public String toString() {
-		StringBuffer pg = new StringBuffer();
-		pg.append(" Page:{ [").append(super.toString()).append("], ");
-		if (records != null) {
-			pg.append("records-size:").append(records.size());
-		} else {
-			pg.append("records is null");
-		}
-		return pg.append(" }").toString();
-	}
+    private static final long serialVersionUID = 1L;
+
+    /**
+     * 查询数据列表
+     */
+    private List<T> records = Collections.emptyList();
+
+    public Page() {
+        /* 注意,传入翻页参数 */
+    }
+
+    public Page(int current, int size) {
+        super(current, size);
+    }
+
+    public List<T> getRecords() {
+        return records;
+    }
+
+    public void setRecords(List<T> records) {
+        this.records = records;
+    }
+
+    @Override
+    public String toString() {
+        StringBuffer pg = new StringBuffer();
+        pg.append(" Page:{ [").append(super.toString()).append("], ");
+        if (records != null) {
+            pg.append("records-size:").append(records.size());
+        } else {
+            pg.append("records is null");
+        }
+        return pg.append(" }").toString();
+    }
 }

+ 59 - 59
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/EntityWrapperTest.java

@@ -1,12 +1,12 @@
 /**
  * Copyright (c) 2011-2020, 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 EntityWrapperS OF ANY KIND, either express or implied. See the
@@ -25,74 +25,74 @@ import com.baomidou.mybatisplus.test.mysql.entity.User;
  * <p>
  * 条件查询测试
  * </p>
- * 
+ *
  * @author hubin
  * @date 2016-08-19
  */
 public class EntityWrapperTest {
 
-	/*
-	 * User 查询包装器
-	 */
-	private EntityWrapper<User> ew = new EntityWrapper<User>();
+    /*
+     * User 查询包装器
+     */
+    private EntityWrapper<User> ew = new EntityWrapper<User>();
 
-	@Test
-	public void test() {
-		/*
-		 * 无条件测试
+    @Test
+    public void test() {
+        /*
+         * 无条件测试
 		 */
-		Assert.assertNull(ew.getSqlSegment());
-	}
+        Assert.assertNull(ew.getSqlSegment());
+    }
 
-	@Test
-	public void test1() {
-		ew.setEntity(new User(1));
-		ew.addFilter("name={0}", "'123'").addFilterIfNeed(false, " ORDER BY id");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" AND name='123'", sqlSegment);
-	}
+    @Test
+    public void test1() {
+        ew.setEntity(new User(1));
+        ew.and("name={0}", "'123'").andIfNeed(false, "id=12");
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" AND name='123'", sqlSegment);
+    }
 
-	@Test
-	public void test2() {
-		ew.setEntity(new User(1));
-		ew.addFilter("name={0} order by id desc", "'123'");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" AND name='123' order by id desc", sqlSegment);
-	}
+    @Test
+    public void test2() {
+        ew.setEntity(new User(1));
+        ew.and("name={0}", "'123'").orderBy("id", false);
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" AND name='123' ORDER BY id DESC ", sqlSegment);
+    }
 
-	@Test
-	public void test3() {
-		ew.setEntity(new User(1));
-		ew.addFilter(" Order By id desc");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" Order By id desc", sqlSegment);
-	}
+    @Test
+    public void test3() {
+        ew.setEntity(new User(1));
+        ew.orderBy("id", false);
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" ORDER BY id DESC ", sqlSegment);
+    }
 
-	@Test
-	public void test21() {
-		ew.addFilter("name={0}", "'123'").addFilterIfNeed(false, " ORDER BY id");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" WHERE name='123'", sqlSegment);
-	}
+    @Test
+    public void test21() {
+        ew.where("name={0}", "'123'").andIfNeed(false, "id=1").orderBy("id");
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" WHERE name='123' ORDER BY id", sqlSegment);
+    }
 
-	@Test
-	public void test22() {
-		ew.addFilter("name={0} order by id desc", "'123'");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" WHERE name='123' order by id desc", sqlSegment);
-	}
+    @Test
+    public void test22() {
+        ew.where("name={0}", "'123'").orderBy("id", false);
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" WHERE name='123' ORDER BY id DESC ", sqlSegment);
+    }
 
-	@Test
-	public void test23() {
-		ew.addFilter(" Order By id desc");
-		String sqlSegment = ew.getSqlSegment();
-		System.err.println(sqlSegment);
-		Assert.assertEquals(" Order By id desc", sqlSegment);
-	}
+    @Test
+    public void test23() {
+        ew.orderBy("id",false);
+        String sqlSegment = ew.getSqlSegment();
+        System.err.println(sqlSegment);
+        Assert.assertEquals(" ORDER BY id DESC ", sqlSegment);
+    }
 
 }

+ 237 - 242
mybatis-plus/src/test/java/com/baomidou/mybatisplus/test/mysql/UserMapperTest.java

@@ -1,12 +1,12 @@
 /**
  * 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
@@ -35,272 +35,267 @@ import com.baomidou.mybatisplus.toolkit.IdWorker;
  * <p>
  * MybatisPlus 测试类
  * </p>
- * 
+ *
  * @author hubin
  * @Date 2016-01-23
  */
 public class UserMapperTest {
 
-	/**
-	 * 
-	 * RUN 测试
-	 * 
-	 * <p>
-	 * MybatisPlus 加载 SQL 顺序:
-	 * </p>
-	 * 1、加载XML中的SQL<br>
-	 * 2、加载sqlProvider中的SQL<br>
-	 * 3、xmlSql 与 sqlProvider不能包含相同的SQL<br>
-	 * <br>
-	 * 调整后的SQL优先级:xmlSql > sqlProvider > crudSql <br>
-	 */
-	public static void main(String[] args) {
-
-		// 加载配置文件
-		InputStream in = UserMapperTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
+    /**
+     * RUN 测试
+     * <p>
+     * <p>
+     * MybatisPlus 加载 SQL 顺序:
+     * </p>
+     * 1、加载XML中的SQL<br>
+     * 2、加载sqlProvider中的SQL<br>
+     * 3、xmlSql 与 sqlProvider不能包含相同的SQL<br>
+     * <br>
+     * 调整后的SQL优先级:xmlSql > sqlProvider > crudSql <br>
+     */
+    public static void main(String[] args) {
+
+        // 加载配置文件
+        InputStream in = UserMapperTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
 
 		/*
-		 * 此处采用 MybatisSessionFactoryBuilder 构建
+         * 此处采用 MybatisSessionFactoryBuilder 构建
 		 * SqlSessionFactory,目的是引入AutoMapper功能
 		 */
-		MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
+        MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
 
 		/*
-		 * 1、数据库字段驼峰命名不需要任何设置 2、当前演示是驼峰下划线混合命名 3、如下开启,表示数据库字段使用下划线命名,该设置是全局的。
+         * 1、数据库字段驼峰命名不需要任何设置 2、当前演示是驼峰下划线混合命名 3、如下开启,表示数据库字段使用下划线命名,该设置是全局的。
 		 * 开启该设置实体可无 @TableId(value = "test_id") 字段映射
 		 */
-		// mf.setDbColumnUnderline(true);
-
-		/**
-		 * 设置,自定义 SQL 注入器
-		 */
-		mf.setSqlInjector(new MySqlInjector());
-
-		SqlSessionFactory sessionFactory = mf.build(in);
-		SqlSession session = sessionFactory.openSession();
-		UserMapper userMapper = session.getMapper(UserMapper.class);
-		System.err.println(" debug run 查询执行 user 表数据变化! ");
-		userMapper.deleteAll();
-
-		/**
-		 * 注解插件测试
-		 */
-		int rlt = userMapper.insertInjector(new User(1L, "1", 1, 1));
-		System.err.println("--------- insertInjector --------- " + rlt);
-
-		/**
-		 * ehcache 缓存测试
-		 */
-		User cacheUser = userMapper.selectOne(new User(1L, 1));
-		print(cacheUser);
-		cacheUser = userMapper.selectOne(new User(1L, 1));
-		print(cacheUser);
-
-		/**
-		 * 插入
-		 */
-		long id = IdWorker.getId();
-		rlt = userMapper.insert(new User(id, "abc", 18, 1));
-		System.err.println("\n--------------insert-------" + rlt);
-		sleep();
-
-		rlt = userMapper.insertSelective(new User("abc", 18));
-		System.err.println("\n--------------insertSelective-------" + rlt);
-		sleep();
-
-		List<User> ul = new ArrayList<User>();
+        // mf.setDbColumnUnderline(true);
+
+        /**
+         * 设置,自定义 SQL 注入器
+         */
+        mf.setSqlInjector(new MySqlInjector());
+
+        SqlSessionFactory sessionFactory = mf.build(in);
+        SqlSession session = sessionFactory.openSession();
+        UserMapper userMapper = session.getMapper(UserMapper.class);
+        System.err.println(" debug run 查询执行 user 表数据变化! ");
+        userMapper.deleteAll();
+
+        /**
+         * 注解插件测试
+         */
+        int rlt = userMapper.insertInjector(new User(1L, "1", 1, 1));
+        System.err.println("--------- insertInjector --------- " + rlt);
+
+        /**
+         * ehcache 缓存测试
+         */
+        User cacheUser = userMapper.selectOne(new User(1L, 1));
+        print(cacheUser);
+        cacheUser = userMapper.selectOne(new User(1L, 1));
+        print(cacheUser);
+
+        /**
+         * 插入
+         */
+        long id = IdWorker.getId();
+        rlt = userMapper.insert(new User(id, "abc", 18, 1));
+        System.err.println("\n--------------insert-------" + rlt);
+        sleep();
+
+        rlt = userMapper.insertSelective(new User("abc", 18));
+        System.err.println("\n--------------insertSelective-------" + rlt);
+        sleep();
+
+        List<User> ul = new ArrayList<User>();
 
 		/* 手动输入 ID */
-		ul.add(new User(11L, "1", 1, 0));
-		ul.add(new User(12L, "2", 2, 1));
-		ul.add(new User(13L, "3", 3, 1));
-		ul.add(new User(14L, "delname", 4, 0));
-		ul.add(new User(15L, "5", 5, 1));
-		ul.add(new User(16L, "6", 6, 0));
-		ul.add(new User(17L, "7", 7, 0));
-		ul.add(new User(18L, "deleteByMap", 7, 0));
+        ul.add(new User(11L, "1", 1, 0));
+        ul.add(new User(12L, "2", 2, 1));
+        ul.add(new User(13L, "3", 3, 1));
+        ul.add(new User(14L, "delname", 4, 0));
+        ul.add(new User(15L, "5", 5, 1));
+        ul.add(new User(16L, "6", 6, 0));
+        ul.add(new User(17L, "7", 7, 0));
+        ul.add(new User(18L, "deleteByMap", 7, 0));
 
 		/* 使用 ID_WORKER 自动生成 ID */
-		ul.add(new User("8", 8, 1));
-		ul.add(new User("9", 9, 1));
-		rlt = userMapper.insertBatch(ul);
-		System.err.println("\n--------------insertBatch----------------" + rlt + "\n\n");
-
-		/**
-		 * 删除
-		 */
-		rlt = userMapper.deleteById(id);
-		System.err.println("---------deleteById------- delete id=" + id + " ,result=" + rlt + "\n\n");
-		sleep();
-
-		Map<String, Object> columnMap = new HashMap<String, Object>();
-		columnMap.put("name", "deleteByMap");
-		rlt = userMapper.deleteByMap(columnMap);
-		System.err.println("---------deleteByMap------- result=" + rlt + "\n\n");
-		sleep();
-
-		List<Long> il = new ArrayList<Long>();
-		il.add(16L);
-		il.add(17L);
-		rlt = userMapper.deleteBatchIds(il);
-		System.err.println("---------deleteBatchIds------- delete id=" + id + " ,result=" + rlt + "\n\n");
-		sleep();
-
-		rlt = userMapper.deleteSelective(new User(14L, "delname"));
-		System.err.println("--------------deleteSelective------------------ result=" + rlt + "\n\n");
-		sleep();
-
-		/**
-		 * <p>
-		 * 修改
-		 * </p>
-		 * 
-		 * updateById 是从 AutoMapper 中继承而来的,UserMapper.xml中并没有申明改sql
-		 * 
-		 */
-
-		rlt = userMapper.updateSelectiveById(new User(12L, "MybatisPlus"));
-		System.err.println("------------------updateSelectiveById---------------------- result=" + rlt + "\n\n");
-		sleep();
-
-		rlt = userMapper.updateById(new User(12L, "update all column", 12, 12));
-		System.err.println("------------------updateById---------------------- result=" + rlt + "\n\n");
-		sleep();
-
-		rlt = userMapper.update(new User("55", 55, 5), new User(15L, "5"));
-		System.err.println("------------------update---------------------- result=" + rlt + "\n\n");
-		sleep();
-
-		rlt = userMapper.updateSelective(new User("00"), new User(15L, "55"));
-		System.err.println("------------------updateSelective---------------------- result=" + rlt + "\n\n");
-		sleep();
+        ul.add(new User("8", 8, 1));
+        ul.add(new User("9", 9, 1));
+        rlt = userMapper.insertBatch(ul);
+        System.err.println("\n--------------insertBatch----------------" + rlt + "\n\n");
+
+        /*
+         * 删除
+         */
+        rlt = userMapper.deleteById(id);
+        System.err.println("---------deleteById------- delete id=" + id + " ,result=" + rlt + "\n\n");
+        sleep();
+
+        Map<String, Object> columnMap = new HashMap<String, Object>();
+        columnMap.put("name", "deleteByMap");
+        rlt = userMapper.deleteByMap(columnMap);
+        System.err.println("---------deleteByMap------- result=" + rlt + "\n\n");
+        sleep();
+
+        List<Long> il = new ArrayList<Long>();
+        il.add(16L);
+        il.add(17L);
+        rlt = userMapper.deleteBatchIds(il);
+        System.err.println("---------deleteBatchIds------- delete id=" + id + " ,result=" + rlt + "\n\n");
+        sleep();
+
+        rlt = userMapper.deleteSelective(new User(14L, "delname"));
+        System.err.println("--------------deleteSelective------------------ result=" + rlt + "\n\n");
+        sleep();
+
+        /*
+         * <p>
+         * 修改
+         * </p>
+         *
+         * updateById 是从 AutoMapper 中继承而来的,UserMapper.xml中并没有申明改sql
+         *
+         */
+
+        rlt = userMapper.updateSelectiveById(new User(12L, "MybatisPlus"));
+        System.err.println("------------------updateSelectiveById---------------------- result=" + rlt + "\n\n");
+        sleep();
+
+        rlt = userMapper.updateById(new User(12L, "update all column", 12, 12));
+        System.err.println("------------------updateById---------------------- result=" + rlt + "\n\n");
+        sleep();
+
+        rlt = userMapper.update(new User("55", 55, 5), new User(15L, "5"));
+        System.err.println("------------------update---------------------- result=" + rlt + "\n\n");
+        sleep();
+
+        rlt = userMapper.updateSelective(new User("00"), new User(15L, "55"));
+        System.err.println("------------------updateSelective---------------------- result=" + rlt + "\n\n");
+        sleep();
 
 		/* 无条件选择更新 */
-		// userMapper.updateSelective(new User("11"), null);
-
-		List<User> userList = new ArrayList<User>();
-		userList.add(new User(11L, "updateBatchById-1", 1, 1));
-		userList.add(new User(12L, "updateBatchById-2", 2, 1));
-		userList.add(new User(13L, "updateBatchById-3", 3, 1));
-		rlt = userMapper.updateBatchById(userList);
-		System.err.println("------------------updateBatchById---------------------- result=" + rlt + "\n\n");
-		sleep();
-
-		/**
-		 * <p>
-		 * 查询
-		 * </p>
-		 */
-		System.err.println("\n------------------selectById----------------------");
-		User user = userMapper.selectById(12L);
-		print(user);
-
-		System.err.println("\n------------------selectBatchIds----------------------");
-		List<Long> idList = new ArrayList<Long>();
-		idList.add(11L);
-		idList.add(12L);
-		List<User> ul0 = userMapper.selectBatchIds(idList);
-		for (int i = 0; i < ul0.size(); i++) {
-			print(ul0.get(i));
-		}
-
-		System.err.println("\n------------------selectByMap-----满足 map 条件的数据----");
-		Map<String, Object> cm = new HashMap<String, Object>();
-		cm.put("test_type", 1);
-		List<User> ul1 = userMapper.selectByMap(cm);
-		for (int i = 0; i < ul1.size(); i++) {
-			print(ul1.get(i));
-		}
-
-		System.err.println("\n------------------selectOne----------------------");
-		User userOne = userMapper.selectOne(new User("abc"));
-		print(userOne);
-
-		System.err.println("\n------------------selectCount----------------------");
-		System.err.println("查询 type=1 总记录数:" + userMapper.selectCount(new User(1)));
-		System.err.println("总记录数:" + userMapper.selectCount(null));
-
-		System.err.println("\n------------------selectList-----所有数据----id--DESC--排序----");
-		List<User> ul2 = userMapper.selectList(new EntityWrapper<User>(null, "age,name"));
-		for (int i = 0; i < ul2.size(); i++) {
-			print(ul2.get(i));
-		}
-
-		System.err.println("\n------------------list 分页查询 ----查询 testType = 1 的所有数据--id--DESC--排序--------");
-		Page<User> page = new Page<User>(1, 2);
-		/*
-		 * 排序 test_id desc
-		 */
-		page.setOrderByField("test_id");
-		page.setAsc(false);
-		EntityWrapper<User> ew = new EntityWrapper<User>(new User(1));
+        // userMapper.updateSelective(new User("11"), null);
+
+        List<User> userList = new ArrayList<User>();
+        userList.add(new User(11L, "updateBatchById-1", 1, 1));
+        userList.add(new User(12L, "updateBatchById-2", 2, 1));
+        userList.add(new User(13L, "updateBatchById-3", 3, 1));
+        rlt = userMapper.updateBatchById(userList);
+        System.err.println("------------------updateBatchById---------------------- result=" + rlt + "\n\n");
+        sleep();
+
+        /*
+         * <p>
+         * 查询
+         * </p>
+         */
+        System.err.println("\n------------------selectById----------------------");
+        User user = userMapper.selectById(12L);
+        print(user);
+
+        System.err.println("\n------------------selectBatchIds----------------------");
+        List<Long> idList = new ArrayList<Long>();
+        idList.add(11L);
+        idList.add(12L);
+        List<User> ul0 = userMapper.selectBatchIds(idList);
+        for (User anUl0 : ul0) {
+            print(anUl0);
+        }
+
+        System.err.println("\n------------------selectByMap-----满足 map 条件的数据----");
+        Map<String, Object> cm = new HashMap<String, Object>();
+        cm.put("test_type", 1);
+        List<User> ul1 = userMapper.selectByMap(cm);
+        for (User anUl1 : ul1) {
+            print(anUl1);
+        }
+
+        System.err.println("\n------------------selectOne----------------------");
+        User userOne = userMapper.selectOne(new User("abc"));
+        print(userOne);
+
+        System.err.println("\n------------------selectCount----------------------");
+        System.err.println("查询 type=1 总记录数:" + userMapper.selectCount(new User(1)));
+        System.err.println("总记录数:" + userMapper.selectCount(null));
+
+        System.err.println("\n------------------selectList-----所有数据----id--DESC--排序----");
+        List<User> ul2 = userMapper.selectList(new EntityWrapper<User>(null, "age,name"));
+        for (User anUl2 : ul2) {
+            print(anUl2);
+        }
+
+        System.err.println("\n------------------list 分页查询 ----查询 testType = 1 的所有数据--id--DESC--排序--------");
+        Page<User> page = new Page<User>(1, 2);
+        EntityWrapper<User> ew = new EntityWrapper<User>(new User(1));
 
 		/*
-		 * 查询字段
+         * 查询字段
 		 */
-		ew.setSqlSelect("age,name");
+        ew.setSqlSelect("age,name");
 
 		/*
-		 * 查询条件,SQL 片段( 注意!程序会自动在 sqlSegmet 内容前面添加 where 或者 and )
+         * 查询条件,SQL 片段(根据常用的写SQL的方式按顺序添加相关条件即可)
 		 */
-		ew.addFilter("name like {0}", "'%dateBatch%'");
-		ew.addFilter(" ORDER BY {0} {1}", page.getOrderByField(), page.isAsc() ? "" : "DESC");
-		List<User> paginList = userMapper.selectPage(page, ew);
-		page.setRecords(paginList);
-		for (int i = 0; i < page.getRecords().size(); i++) {
-			print(page.getRecords().get(i));
-		}
-		System.err.println(" 翻页:" + page.toString());
-
-		System.err.println("\n---------------xml---selectListRow 分页查询,不查询总数(此时可自定义 count 查询)----无查询条件--------------");
-		// TODO 查询总数传 Page 对象即可
-		List<User> rowList = userMapper.selectListRow(new Pagination(0, 2, false));
-		for (int i = 0; i < rowList.size(); i++) {
-			print(rowList.get(i));
-		}
+        ew.and("name like {0}", "'%dateBatch%'")
+                .and("age={0}", 3)
+                .orderBy("age,name", true);
+        List<User> paginList = userMapper.selectPage(page, ew);
+        page.setRecords(paginList);
+        for (int i = 0; i < page.getRecords().size(); i++) {
+            print(page.getRecords().get(i));
+        }
+        System.err.println(" 翻页:" + page.toString());
+
+        System.err.println("\n---------------xml---selectListRow 分页查询,不查询总数(此时可自定义 count 查询)----无查询条件--------------");
+        // TODO 查询总数传 Page 对象即可
+        List<User> rowList = userMapper.selectListRow(new Pagination(0, 2, false));
+        for (User aRowList : rowList) {
+            print(aRowList);
+        }
 
 		/*
 		 * 用户列表
 		 */
-		System.err.println(" selectList EntityWrapper == null \n");
-		paginList = userMapper.selectList(null);
-		for (int i = 0; i < paginList.size(); i++) {
-			print(paginList.get(i));
-		}
-
-		/**
-		 * 自定义方法,删除测试数据
-		 */
-		rlt = userMapper.deleteAll();
-		System.err.println("清空测试数据! rlt=" + rlt);
-
-		/**
-		 * 提交
-		 */
-		session.commit();
-	}
-
-	/*
-	 * 打印测试信息
-	 */
-	private static void print(User user) {
-		sleep();
-		if (user != null) {
-			System.out.println("\n user: id=" + user.getId() + ", name=" + user.getName() + ", age=" + user.getAge()
-					+ ", testType=" + user.getTestType());
-		} else {
-			System.out.println("\n user is null.");
-		}
-	}
-
-	/*
-	 * 慢点打印
-	 */
-	private static void sleep() {
-		try {
-			Thread.sleep(1000);
-		} catch (InterruptedException e) {
-			e.printStackTrace();
-		}
-	}
+        System.err.println(" selectList EntityWrapper == null \n");
+        paginList = userMapper.selectList(null);
+        for (User aPaginList : paginList) {
+            print(aPaginList);
+        }
+
+        /**
+         * 自定义方法,删除测试数据
+         */
+        rlt = userMapper.deleteAll();
+        System.err.println("清空测试数据! rlt=" + rlt);
+
+        /**
+         * 提交
+         */
+        session.commit();
+    }
+
+    /*
+     * 打印测试信息
+     */
+    private static void print(User user) {
+        sleep();
+        if (user != null) {
+            System.out.println("\n user: id=" + user.getId() + ", name=" + user.getName() + ", age=" + user.getAge()
+                    + ", testType=" + user.getTestType());
+        } else {
+            System.out.println("\n user is null.");
+        }
+    }
+
+    /*
+     * 慢点打印
+     */
+    private static void sleep() {
+        try {
+            Thread.sleep(1000);
+        } catch (InterruptedException e) {
+            e.printStackTrace();
+        }
+    }
 }