我的< 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);
}
}
结果: