目录
in语句:使用foreach标签
mapper层
List<String> findNamesByDeptIds(List<String> deptIds);
mapper.xml
<select id="findNamesByDeptIds" parameterType="java.lang.String" resultType="java.lang.String">
select depart_name
from t_base_depart
where
<foreach collection="deptIds" item="deptId" open="id in (" close=")" separator=",">
#{deptId}
</foreach>
</select>
属性介绍
collection表示集合
赋值传参名字deptIds,不用加#{}
item表示给内部数据取名
open表示语句开始前的输入
close表示语句结束时的输入
separator表示每个item之间使用某个符号隔开
注意:
parameterType和resultType是集合时,只需要赋值泛型类型即可
where标签 if标签 trim标签:
mapper层
List<Dept> findByIdName(Integer id,String name);
mapper.xml
<select id="findByIdName" resultType="Dept">
select *
from dept
<where>
<if test="id != null">and id = #{param1}</if>
<if test="name != null and name != ''">and name = #{param2}</if>
</where>
</select>
where标签
表示where和and连接在一起时自动删除and
if标签
表示test里面的条件满足时,输出标签中间的数据
test中的条件一般限制字符串类型不为null或者' ',其他类型限制不为null(设置包装类的好处)
注意
传多个参数,使用param1和param2来区别
where标签可以使用trim替代,更灵活
<select id="findByIdName" resultType="Dept">
select *
from dept
<trim prefix="where" prefixOverrides="and">
<if test="id != null">and id = #{param1}</if>
<if test="name != null and name != ''">and name = #{param2}</if>
</trim>
</select>
trim标签属性
prefix表示以xxx开头
prefixOverrides表示若标签中间内容以xxx开头,就删除
suffix表示以xxx结尾
suffixOverrides表示若标签中间内容以xxx结尾,就删除
choose when标签可以代替if标签
<select id="findByIdName" resultType="Dept">
select *
from dept
<trim prefix="where" prefixOverrides="and">
<choose>
<when test="id != null">and id = #{param1}</when>
<when test="name != null and name != ''">and name = #{param2}</when>
</choose>
</trim>
</select>
set标签
<update id="update" parameterType="Dept">
update dept
<set>
<if test="name != null and name != ''">name = #{name},</if>
<if test="address != null and address != ''">address = #{address}</if>
</set>
where id = #{id}
</update>
set标签
若标签中间内容以","结尾,就自动去掉
注意:
写sql语句时表的字段和实体类的属性需要区别!!!
test属性里面一般都是实体类的属性