持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第10天,点击查看活动详情
5. < set>标签
使用set标签可以将动态的配置 SET 关键字,并剔除追加到条件末尾的任何不相关的逗号。使用 if+set 标签修改后,在进行表单更新的操作中,哪个字段中有值才去更新,如果某项为 null 则不进行更新,而是保持数据库原值。切记:至少更新一列。
<update id="updateBySet" parameterType="users">\
update users\
<set>\
<if test="userName != null and userName != ''">\
username = #{userName},\
</if>\
<if test="birthday != null">\
birthday = #{birthday},\
</if>\
<if test="sex != null and sex != ''">\
sex =#{sex},\
</if>\
<if test="address != null and address !=''">\
address = #{address}\
</if>\
</set>\
where id = #{id}\
</update>
测试:
@Test\
public void testUpdateSet()throws Exception{\
// Users u = new Users("哈哈",new Date(),"1","北京亦庄大兴");\
//Users u = new Users(3,"不知道",sf.parse("1998-08-08"),"2","北京亦庄大兴888");\
Users u = new Users();\
u.setId(2);\
u.setUserName("认识张三不");\
//u.setSex("2");\
//u.setBirthday(sf.parse("2000-01-01"));\
int num = usersMapper.updateBySet(u);\
//切记切记:必须提交事务\
sqlSession.commit();\
System.*out*.println(num);\
}
运行结果:
6. < foreach>标签
< foreach>主要用来进行集合或数组的遍历,主要有以下参数:
- collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。\
- item :循环体中的具体对象。支持属性的点路径访问,如item.age,item.info.details,在list和数组中是其中的对象,在map中是value。\
- index :在list和数组中,index是元素的序号,在map中,index是元素的key,该参数可选。\
- open :表示该语句以什么开始\
- close :表示该语句以什么结束\
- separator :表示元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。