学习目的:在Java自学之mybatis:动态SQL之if标签中提到“查询的字段增加,可以继续添加if标签”,但是同时满足了多个查询条件,拼接的SQL语句就会出现语法错误,所以就需要另外一些标签来排除语法错误,本节学习的三个标签都可以达到这个目的。
Part 1
可能出现的语法错误分析:
select * from product_ where
and name like concat('%',#{name},'%')
and price>#{price}
当上面两个if同时满足,那么SQL语句就会拼接成select * from product_ where and name like concat('%',#{name},'%') and price>#{price},很明显第一个and是多余的,此时就出现了SQL语法错误。
Part 2
where标签可以自动覆盖第一个and或者or,part 1中的正确配置如下(注意select * from product_后面不用写where,下同):
select * from product_
and name like concat('%',#{name},'%')
and price>#{price}
Part 3
在修改数据时,要把if标签写在set标签里面。set标签可以自动删除SQL语句if标签末尾多余的“,”。
update product_
name=#{name},
price=#{price}
where id=#{id}
如果不使用set标签,当第二个if不成立时,拼装成的SQL语句是:update product_ set name=#{name}, where id=#{id},此时{name}后面的“,”多余,会造成语法错误。上面使用set标签的正确配置就可以自动删除该“,”。
Part 4
trim标签是用户可以自定义的标签,同样也可以实现where标签和set标签所实现的功能。使用trim标签替换where标签和set标签,分别使用下面的配置:
替换where
......
替换set
......