Java|Java Mybatis批量修改封装详解

重点重点重点,不然会报错

连接数据库url后面加个参数
allowMultiQueries=true
用习惯了 insertList 怎么能没有 updateList呢
就两个类 直接上代码
package com.lancabbage.gorgeous.utils.mybatis; import org.apache.ibatis.mapping.MappedStatement; import tk.mybatis.mapper.entity.EntityColumn; 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.Set; import static tk.mybatis.mapper.mapperhelper.SqlHelper.whereVersion; /** * ListUpdateProvider实现类,批量修改方法实现类 * * @author lanyanhua */public class ListUpdateProvider extends MapperTemplate {public ListUpdateProvider(Class mapperClass, MapperHelper mapperHelper) {super(mapperClass, mapperHelper); }///**//* 通过主键更新全部字段//*//* @param ms//*///public String updateByPrimaryKey(MappedStatement ms) {//Class entityClass = getEntityClass(ms); //StringBuilder sql = new StringBuilder(); //sql.append(SqlHelper.updateTable(entityClass, tableName(entityClass))); //sql.append(SqlHelper.updateSetColumns(entityClass, null, false, false)); //sql.append(SqlHelper.wherePKColumns(entityClass, true)); //return sql.toString(); //}/*** 通过主键更新不为null的字段** @param ms* @return*/public String updateByPrimaryKeySelectiveList(MappedStatement ms) {Class entityClass = getEntityClass(ms); StringBuilder sql = new StringBuilder(); sql.append(""); //setsql.append(SqlHelper.updateTable(entityClass, tableName(entityClass))); sql.append(SqlHelper.updateSetColumns(entityClass, "record", true, isNotEmpty())); //wheresql.append(""); Set columnSet = EntityHelper.getPKColumns(entityClass); //当某个列有主键策略时,不需要考虑他的属性是否为空,因为如果为空,一定会根据主键策略给他生成一个值for (EntityColumn column : columnSet) {sql.append(" AND ").append(column.getColumnEqualsHolder("record")); }sql.append(whereVersion(entityClass)); sql.append(""); sql.append(" ; \n"); sql.append(""); return sql.toString(); }}

package com.lancabbage.gorgeous.utils.mybatis; import org.apache.ibatis.annotations.UpdateProvider; import tk.mybatis.mapper.annotation.RegisterMapper; import java.util.List; /** * 通用Mapper接口,更新 * * @param 不能为空 * @author lanyanhua */@RegisterMapperpublic interface ListUpdateByPrimaryKeySelectiveMapper {/*** 根据主键更新属性不为null的值** @param record* @return*/@UpdateProvider(type = ListUpdateProvider.class, method = "dynamicSQL")int updateByPrimaryKeySelectiveList(List record); }

我是使用的是Tk.mybatis。代码是复制的原来的updateByPrimaryKeySelective的代码进行的微调
保证最终的结构类似这种就ok
UPDATE project id = id,name = #{record.name},remote_path = #{record.remotePath},create_time = #{record.createTime},is_show = #{record.isShow},display_order = #{record.displayOrder},AND id = #{record.id}

使用 就和其他的一样 在你的Mapper类上继承这个类ListUpdateByPrimaryKeySelectiveMapper就好了
public interface BaseMapper extends Mapper, MySqlMapper, ListUpdateByPrimaryKeySelectiveMapper {}

总结 【Java|Java Mybatis批量修改封装详解】本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注脚本之家的更多内容!

    推荐阅读