MyBatis-Plus 3 实现批量新增和批量修改

1、批量更新

mapper 接口:批量方法插入 

void batchInsert(@Param("users") List users)

mapper xml: 批量插入xml


      insert into biz_user (id, name, sex) values
     
     (#{item.id},#{item.name},#{item.sex})
     

2、批量插入

mapper 接口:批量方法插入 

void batchUpdate(@Param("users") List users)

mapper xml: 批量更新xml (通过拼接SQL语句)


 

 
    
 
    
        update biz_user set
        name = #{item.name},
        sex = #{item.sex}
        where id= #{item.id}
    
 

温馨提示: 

在数据库连接配置中必须添加 &allowMultiQueries=true,

jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai

 &allowMultiQueries=true 意为 允许批量更新,否则在执行SQL时会报以下异常:

Error updating database.  Cause: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'update biz_user set
            name = 'zzg',
            sex = '1'

报错原因:

是因为spring boot配置文件中,关于数据库的连接配置,并没有允许进行批量更新的操作。

这种方式就是通过SQL拼接,单条单条的进行更新,如果行数多的情况下给不建议使用。

 

mapper xml: 批量更新xml (通过case when语句)


    update biz_user
    
        
            
                
                    when id= #{item.id} then #{item.name}
                
            
        
        
            
                
                    when id=#{item.id} then #{item.sex}
                
            
        
    
    where
    
        id= #{item.id}
    

通过case when语句进行批量更新,只要一条SQL语句.

上面的案列是针对多个字段的情况;如果只是更新单个字段,我们可以这么写:


    update biz_user
        set name = CASE
        
            when id = #{item.id} then #{item.name}
        
        END
        WHERE id in
        
            #{item.id}
        
        

3、自定义分页

页面请求参数
- 页面显示条数 size
- 第page页面

mapper 接口:分页查询

List page(T t,  Integer start, Integer size)

mapper xml: 分页查询


你可能感兴趣的:(MyBaties(基础篇),mybatis,java,开发语言)