Sql中可将重复的sql提取出来,使用时用include引用即可,最终达到sql重用的目的。
sql片段定义:
<sql id="selector">
select * from user
</sql>
使用:
<include refid="selector"></include>
where 可以去掉第一个前 and
<select id="queryUserWhere" parameterType="com.it.mybatis.pojo.User" resultType="com.it.mybatis.pojo.User">
<include refid="selector"></include>
<where>
<if test="sex != null and sex !=''">
and sex = #{sex}
</if>
<if test="username != null and username !=''">
and username = #{username}
</if>
</where>
</select>
foreach标签
1)foreach标签,进行遍历
2)collection:遍历的集合,这里是类的 id 属性
3)item:遍历的项目,可以随便写,和后面的#{}里面要一致
4)open:在前面添加的sql片段
5)close:在结尾处添加的sql片段
6)separator:指定遍历的元素之间使用的分隔符
如果不用包装类,集合,数组--》collection=list ,array
<select id="queryUserById" parameterType="com.it.mybatis.pojo.QueryVo" resultType="com.it.mybatis.pojo.User">
<include refid="selector"></include>
<where>
<foreach collection="id" item="id"
open="id in (" close=")" separator=",">
#{id}
</foreach>
</where>
</select>