if标签
<if test="(id)!=null and (id!='')">
AND id = #{id}
</if>
<if test="(user.balance)!=null and(user.balance!='')">
AND balance = #{user.balance}
</if>
Test中此写的是表达式,ognl取值+sql语句的写法
这样写出现一个问题,if标签中的and关键字没法放,前后都可能出错。
while标签
能够自动删除if标签中的前and
如果后面的条件都不成立,where关键字也可以省略。
foreach标签
1.如果传入对象:
<!--对象-->
<select id="findUserByObj" parameterType="cn.hd.pojo.QueryVo"resultType="cn.hd.pojo.User">
<include refid="selectUser"></include>
<where> id in
<foreach collection="ids" item="id"separator="," open="(" close=")">
#{id}
</foreach>
</where>
</select>
如果使用对象的话,collection中的值必须是实体类中的属性名,item中的id是自己定义的一个名字,理解为是该集合中的一个子元素,
2.如果传入数组:
<!--数组-->
<select id="findUserByArray" parameterType="java.util.Arrays" resultType="cn.hd.pojo.User">
<include refid="selectUser"></include>
<where> id in
<foreach collection="array" item="id" separator=","open="(" close=")">
#{id}
</foreach>
</where>
</select>
3.如果传入集合
<select id="findUserByList" parameterType="java.util.ArrayList"resultType="cn.hd.pojo.User">
<include refid="selectUser"></include>
<where> id in
<foreach collection="list" item="id" separator=","open="(" close=")">
#{id}
</foreach>
</where>
</select>
Sql片段:
首先要将公共的sql语句提取出来
<sql id="selectUser">
SELECT * FROM user
</sql>
<select id="findUserById" parameterType="cn.hd.pojo.QueryVo"resultType="cn.hd.pojo.User">
<includerefid="selectUser"></include>将上面的sql语句引入进来
<where>