xxxMapper 中的 select 标签中的 if 和 where 标签
<!-- 使用动态 sql 进行用户信息综合查询 -->
<select id="getListByConditions" resultType="user" parameterType="user">
select * from user
<!-- where 标签可以自动添加 where 和去除条件中的第一个 and -->
<where>
<if test="username != null">
and username like '%${username}%'
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</where>
</select>
sql 片段
需求:将上边实现的动态 sql 判断代码块抽取出来,组成一个 sql 片段,其他的 statement 中就可以引用该 sql 片段。
1、定义 sql 片段( xxxMapper的mapper标签中定义 ):
<!-- 定义 sql 片段
id: sql 片段的唯一标识
经验:1、要基于单表来定义sql片段,这样在进行多表查询时引用才方便,可重用性才高
2、在 sql 片段中不要包括where,where写在具体的查询的select标签中 -->
<sql id="query_user_where">
<if test="username != null">
and username like '%${username}%'
</if>
<if test="sex != null">
and sex=#{sex}
</if>
</sql>
2、引用 sql 片段:
<select id="getListByConditions" resultType="user" parameterType="user">
select * from user
<where>
<!-- 引用 sql 片段,可以引用多个
refid:所引用的 sql 片段的 id,如果 refid 指定的 sql 片段 不在本 xxxMapper.xml 文件中,需要在前面加 namespace的值 -->
<include refid="query_user_where"></include>
</where>
</select>
xxxMapper 中的 select 标签中的 foreach 标签
遍历集合:
<select id="" parameterType="user" resultType="">
<!-- 使用 foreach 遍历传入的 user 对象中的的id 的 list集合
实现这个sql的拼接:and (id=1 or id=10 or id=16) -->
<!-- collection:指定输入对象中的集合名称
item:每次遍历生成的对象
open:开始遍历时拼接的串
close:结束遍历时拼接的串
separator:遍历的两个对象之间需要拼接的串 -->
<foreach collection="ids" item="user_id" open="abd (" close=")" separator="or">
<!-- 每个遍历需要拼接的串 -->
id=#{user_id}
</foreach>
</select>