Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat:增加批量update功能 #741

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package tk.mybatis.mapper.additional.update.batch;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.UpdateProvider;
import tk.mybatis.mapper.annotation.RegisterMapper;
import tk.mybatis.mapper.weekend.Fn;

import java.util.List;

@RegisterMapper
public interface BatchUpdatePropertyByPrimaryKeyMapper<T, PK> {

/**
* 多条数据更新同一字段为相同值
* @param fn 字段名
* @param value 更新的字段值
* @param primaryKeys 数据主键集合
* @return
*/
@UpdateProvider(type = BatchUpdatePropertyByPrimaryKeyProvider.class, method = "dynamicSQL")
int batchUpdateFieldByIdList(@Param("fn") Fn<T, ?> fn, @Param("value") Object value, @Param("idList") List<PK> primaryKeys);

/**
* 多条数据更新多个字段为相同值
* @param fieldValues 更新字段及更新值
* @param primaryKeys 数据主键集合
* @return
*/
@UpdateProvider(type = BatchUpdatePropertyByPrimaryKeyProvider.class, method = "dynamicSQL")
int batchUpdateFieldListByIdList(@Param("fieldList") List<FieldValue<T>> fieldValues, @Param("idList") List<PK> primaryKeys);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package tk.mybatis.mapper.additional.update.batch;

import org.apache.ibatis.mapping.MappedStatement;
import tk.mybatis.mapper.MapperException;
import tk.mybatis.mapper.entity.EntityColumn;
import tk.mybatis.mapper.entity.EntityTable;
import tk.mybatis.mapper.mapperhelper.EntityHelper;
import tk.mybatis.mapper.mapperhelper.MapperHelper;
import tk.mybatis.mapper.mapperhelper.MapperTemplate;
import tk.mybatis.mapper.mapperhelper.SqlHelper;

import java.util.List;
import java.util.Set;

public class BatchUpdatePropertyByPrimaryKeyProvider extends MapperTemplate {

public BatchUpdatePropertyByPrimaryKeyProvider(Class<?> mapperClass, MapperHelper mapperHelper) {
super(mapperClass, mapperHelper);
}

public String batchUpdateFieldByIdList(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
StringBuilder sql = new StringBuilder();
sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
appendSet(sql, entityClass);
appendWhereIdList(sql, entityClass, true);
return sql.toString();
}

public String batchUpdateFieldListByIdList(MappedStatement ms) {
Class<?> entityClass = getEntityClass(ms);
StringBuilder sql = new StringBuilder();
sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass)));
appendFileListSet(sql, entityClass);
appendWhereIdList(sql, entityClass, true);
return sql.toString();
}

private void appendSet(StringBuilder sql, Class<?> entityClass) {
sql.append("<set>");
//通过实体类名获取运行时属性对应的字段
String ognl = new StringBuilder("${@")
.append(getProviderName())
.append("@getColumnByProperty(@java.lang.Class@forName(\"")
.append(entityClass.getName())
.append("\"), @tk.mybatis.mapper.weekend.reflection.Reflections@fnToFieldName(fn))}").toString();
sql.append(ognl + " = #{value}\n");
sql.append("</set>");
}

private void appendWhereIdList(StringBuilder sql, Class<?> entityClass, boolean useVersion) {
Set<EntityColumn> columnList = EntityHelper.getPKColumns(entityClass);
if (columnList.size() == 1) {
EntityColumn column = columnList.iterator().next();
sql.append("<bind name=\"notEmptyListCheck\" value=\"@tk.mybatis.mapper.additional.update.batch.BatchUpdatePropertyByPrimaryKeyProvider@notEmpty(");
sql.append("idList, 'idList 不能为空')\"/>");
sql.append("<where>");
sql.append("<foreach collection=\"idList\" item=\"id\" separator=\",\" open=\"");
sql.append(column.getColumn());
sql.append(" in ");
sql.append("(\" close=\")\">");
sql.append("#{id}");
sql.append("</foreach>");
if (useVersion) {
sql.append(SqlHelper.whereVersion(entityClass));
}
sql.append("</where>");
} else {
throw new MapperException("继承 BatchUpdatePropertyByPrimaryKeyMapper 方法的实体类[" + entityClass.getCanonicalName() + "]中必须只有一个带有 @Id 注解的字段");
}
}

private void appendFileListSet(StringBuilder sql, Class<?> entityClass) {
sql.append("<set>");
sql.append("<foreach collection=\"fieldList\" item=\"field\" separator=\",\" >");
//通过实体类名获取运行时属性对应的字段
String ognl = "${@" +
getProviderName() +
"@getColumnByProperty(@java.lang.Class@forName(\"" +
entityClass.getName() +
"\"), @tk.mybatis.mapper.weekend.reflection.Reflections@fnToFieldName(field.fn))}";
sql.append(ognl + " = #{field.value}\n");
sql.append("</foreach>");
sql.append("</set>");

}

private String getProviderName() {
return BatchUpdatePropertyByPrimaryKeyProvider.class.getName();
}

/**
* 根据实体Class和属性名获取对应的表字段名
*
* @param entityClass 实体Class对象
* @param property 属性名
* @return
*/
public static String getColumnByProperty(Class<?> entityClass, String property) {
EntityTable entityTable = EntityHelper.getEntityTable(entityClass);
EntityColumn entityColumn = entityTable.getPropertyMap().get(property);
return entityColumn.getColumn();
}

/**
* 保证 idList 不能为空
*
* @param list
* @param errorMsg
*/
public static void notEmpty(List<?> list, String errorMsg){
if(list == null || list.size() == 0){
throw new MapperException(errorMsg);
}
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package tk.mybatis.mapper.additional.update.batch;

import tk.mybatis.mapper.weekend.Fn;

public class FieldValue<T> {

/**
* 字段名
* 形式必须是 类::方法
* e.g. Country::getCountryname
*/
private Fn<T, ?> fn;

/**
* 更新的字段值
*/
private Object value;

public FieldValue(Fn<T, ?> fn, Object value) {
this.fn = fn;
this.value = value;
}

public FieldValue() {
}

public Fn<T, ?> getFn() {
return fn;
}

public void setFn(Fn<T, ?> fn) {
this.fn = fn;
}

public Object getValue() {
return value;
}

public void setValue(Object value) {
this.value = value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package tk.mybatis.mapper.additional.update.batch;

import org.apache.ibatis.session.SqlSession;
import org.junit.Assert;
import org.junit.Test;
import tk.mybatis.mapper.additional.BaseTest;
import tk.mybatis.mapper.additional.Country;

import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* @author goldhuang
* @Description: 验证批量更新
* @date 2020-04-02
*/
public class BatchUpdatePropertyByPrimaryKeyTest extends BaseTest {

/**
* 获取 mybatis 配置
*
* @return
*/
protected Reader getConfigFileAsReader() throws IOException {
URL url = getClass().getResource("mybatis-config.xml");
return toReader(url);
}

;

@Test
public void testBatchUpdateFieldByIdList() {
SqlSession sqlSession = getSqlSession();
try {
tk.mybatis.mapper.additional.update.batch.CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);

//(1, 'Angola', 'AO', 1)
Country old1 = mapper.selectByPrimaryKey(1L);
//(2, 'Afghanistan', 'AF', 1)
Country old2 = mapper.selectByPrimaryKey(2L);

int updateCount = mapper.batchUpdateFieldByIdList(Country::getCountryname, "Gold", Arrays.asList(old1.getId(), old2.getId()));
Assert.assertEquals(2, updateCount);

old1 = mapper.selectByPrimaryKey(1L);
old2 = mapper.selectByPrimaryKey(2L);

Assert.assertEquals(1L, old1.getId().longValue());
Assert.assertEquals(2L, old2.getId().longValue());
Assert.assertEquals("Gold", old1.getCountryname());
Assert.assertEquals("Gold", old2.getCountryname());
} finally {
sqlSession.close();
}
}

@Test(expected = Exception.class)
public void testBatchUpdateFieldByEmptyIdList() {
SqlSession sqlSession = getSqlSession();
try {
tk.mybatis.mapper.additional.update.batch.CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
mapper.batchUpdateFieldByIdList(Country::getCountryname, "Gold", new ArrayList<>());
} finally {
sqlSession.close();
}
}

@Test
public void batchUpdateFieldListByIdList() {
SqlSession sqlSession = getSqlSession();
try {
tk.mybatis.mapper.additional.update.batch.CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);

//(1, 'Angola', 'AO', 1)
Country old1 = mapper.selectByPrimaryKey(1L);
//(2, 'Afghanistan', 'AF', 1)
Country old2 = mapper.selectByPrimaryKey(2L);

List<FieldValue<Country>> fieldValues = new ArrayList<>();
fieldValues.add(new FieldValue<>(Country::getCountrycode, "GD"));
fieldValues.add(new FieldValue<>(Country::getCountryname, "Gold"));

int updateCount = mapper.batchUpdateFieldListByIdList(fieldValues, Arrays.asList(old1.getId(), old2.getId()));
Assert.assertEquals(2, updateCount);

old1 = mapper.selectByPrimaryKey(1L);
old2 = mapper.selectByPrimaryKey(2L);

Assert.assertEquals(1L, old1.getId().longValue());
Assert.assertEquals(2L, old2.getId().longValue());
Assert.assertEquals("Gold", old1.getCountryname());
Assert.assertEquals("Gold", old2.getCountryname());
Assert.assertEquals("GD", old1.getCountrycode());
Assert.assertEquals("GD", old2.getCountrycode());
} finally {
sqlSession.close();
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package tk.mybatis.mapper.additional.update.batch;

import tk.mybatis.mapper.additional.Country;
import tk.mybatis.mapper.common.BaseMapper;

public interface CountryMapper extends BaseMapper<Country>, BatchUpdatePropertyByPrimaryKeyMapper<Country, Long> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2014-2017 [email protected]
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy
~ of this software and associated documentation files (the "Software"), to deal
~ in the Software without restriction, including without limitation the rights
~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
~ copies of the Software, and to permit persons to whom the Software is
~ furnished to do so, subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in
~ all copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
~ THE SOFTWARE.
-->

<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:mem:deffer" />
<property name="username" value="sa" />
</dataSource>
</environment>
</environments>

<mappers>
<mapper class="tk.mybatis.mapper.additional.update.batch.CountryMapper"/>
</mappers>

</configuration>