批量修改的小技巧

博客主要介绍了在Java中使用MySQL修改行数据的不同情况。一是只修改一个参数且结果相同时的SQL语句及在mybatis - plus中的操作;二是需要修改多个结果、多个条件时,包括只改一个参数条件不同值不同,以及修改多个参数条件不同值也不同的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、在修改行数据 只修改一个参数 并且修改的结果都一样时

1、sql语句为:

#也就是说 参数是多个 但是条件确是多个
update t_learn_mysql
	set `password` = '123456'
	where id BETWEEN 2 and 5 ;

2、在mybatis-plus中:

//可以通过 **mapper.update()修改
	//new 一个新的对象  把需要修改的参数传递进去 别的参数为空
	User user = new User();
	user.setPassword("123456");
	// 在修改的时候 只需要 保证条件正确即可
	usermapper.update(user,new UpdateWrapper<User>().between("id",2,5));

二、当需要修改的 有多个结果 多个条件的时候

	可以通过 case when then 的组合来完成数的批量修改
	注:在项目中  sql语句可以长一些   但是应该避免重复的连接数据库

1、sql语句为:

update t_learn_mysql 
	set 
		account = 
			case id
				when  1 then 'xiuer' 
				when  2 then 'aimafan'
			end
	where 
		id in(1,2)
;

2、mybatis 或者mybatis-plus连接, 只修改一个参数 ,并且条件不同 值也不同 的时候

@Update({"<script>"+
			" update t_learn_mysql  " +
       "<trim prefix ='set' prefixOverrides=',' > " +
           "<trim prefix ='account = case' suffix='end'>" +
               "<foreach collection ='list' item ='user' index = 'index'> " +
                   "when id = #{user.id} then #{user.account} " +
               "</foreach>" +
           "</trim> " +
       "</trim> " +
       "where  id in " +
           "<foreach collection ='list' item ='user' index ='index' separator=',' open='(' close=')'  > " +
                "#{user.id} " +
           "</foreach>" +
       " </script>" })
int updateBatn(@Param("list")List<User> list);

3、mybatis 或者mybatis-plus连接 ,修改多个参数 条件不同,值也不同的时候

@Update({"<script>"+
			" update t_learn_mysql  " +
       "<trim prefix ='set' prefixOverrides=',' > " +
           "<trim prefix ='account = (case' suffix='end),'>" +
               "<foreach collection ='list' item ='user' index = 'index'> " +
                   "when id = #{user.id} then #{user.account} " +
               "</foreach>" +
           "</trim> " +
           "<trim prefix ='password= (case' suffix='end)'>" +
               "<foreach collection ='list' item ='user' index = 'index'> " +
                   "when id = #{user.id} then #{user.password} " +
               "</foreach>" +
           "</trim> " +
       "</trim> " +
       "where  id in " +
           "<foreach collection ='list' item ='user' index ='index' separator=',' open='(' close=')'  > " +
                "#{user.id} " +
           "</foreach>" +
       " </script>" })
int updateBatn(@Param("list")List<User> list);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值