1、foreach
实现遍历功能,常用于对List和map进行遍历,拼接sql
#{} 和 ${} 在使用中的技巧和建议
(1)不论是单个参数,还是多个参数,一律都建议使用注解@Param("")
(2)能用 #{} 的地方就用 #{},不用或少用 $ {} ,#{}自动加 ’ ',${} 不自动加
(3)表名作参数时,必须用 ${}。如:select * from ${tableName}
(4)order by 时,必须用 ${}。如:select * from t_user order by ${columnName}
(5)使用 ${} 时,要注意何时加或不加单引号
1、遍历 List
select
<foreach collection="colnameList" item="colname" separator=",">
${colname}
</foreach>
from table1
2、遍历 Map
<foreach collection="()" item="value" index="key">
${key} = #{value}
</foreach>
3、遍历 List ,把遍历结果放在 sql in 条件中
select *
from table1
where id in
<foreach collection="idList" item="id" open="(" close=")" separator=",">
#{id}
</foreach>
2、where 标签
可以自动删掉首个 and 或者 or,使用where标签就不用再写 一句 1=1 进行sql 连接了
select *
from table1
<where>
and id=1
<where>