MyBatis 动态元素 set元素

我的< set >元素主要用在UPDATE更新操作

< set >标签可以动态的配置 SET 关键字,并自动剔除属性设置的最后一个逗号。
在UPDATE更新操作中使用set标签加if标签动态配置SQL语句,可以轻松的设置哪些属性更改而哪些属性保持原值,不向以前那样,修改一个属性也要改动此行所有的属性,增强了sql语句的性能。

CM1.xml(一个mapper)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<!-- namespace表示命名空间-->
<mapper namespace="com.itheima.mapper.CM1">
	<!-- parameterType 传入的参数类型 -->
	<update id="U" parameterType="com.itheima.po.Account">
		update account
		<set>
			<if test="username != null and username != '' ">
				username=#{username},
			</if>
			<if test="balance != null and balance >= 0 ">
				balance=#{balance},
			</if>
		</set>
		where id=#{id}
	</update>
</mapper>

拼接手法:

基础的SQL语句:

update account set where id=#{id}

< if test="username != null and username != ‘’ " >
如果用户名(username)不为空的话,SQL语句为:

update account set username=#{username}  where id=#{id}

set标签会自动剔除属性设置的最后一个逗号,所以虽然在if语句中存在逗号,但这里是没有的

< if test=“balance != null and balance >= 0”>
如果balance(余额)也不为空且大于0的话,SQL语句为:

update account set username=#{username},balance=#{balance}  where id=#{id}

set标签会只剔除最后一个属性值后的逗号

如果前一个if条件不成立,后一个条件成立的话,SQL语句为:

update account set balance=#{balance}  where id=#{id}

小小的贴个代码图

//update set属性
	@Test
	public void upDateTest() throws Exception  {
		SqlSession session=MyBatisUtils.getSqlSession();
		
		Account account=new Account();
		account.setId(1);
		account.setUsername("小明");
		account.setBalance(8000);
		
		int num=session.update("com.itheima.mapper.CM1.U", account);
		session.commit();
		session.close();
		
		if (num>=1) {
			System.out.println("更新成功!");
			findAccountByIdTest(1);
		}
	}

结果:
也许图片失效了哦

MyBatis动态SQL中的一些元素 if、set、trim、choose、foreach、bind

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值