标签:不为 efi student span rom 删除 sep 数组 hlist
代码:
<!-- 需要注意的事项:
01. 在xml文件中 特殊字符的使用
&&必须换成 and或者 &
< <
> >
<= <=
>= >=
‘ '
" "
02.因为不确定用户输入的到底是哪个参数 所以 where 之后必须加上 1=1 而且 每个条件之前加上 and
-->
<select id="selectStudentsByIf" resultType="Student">
select id,name,age from student where 1=1
<if test="name!=null and name!=‘‘ ">
and name like concat(‘%‘,#{name},‘%‘)
</if>
<if test="age>0">
and age>#{age}
</if>
</select>
代码:
<!--动态sql where -->
<select id="selectStudentsByWhere" resultType="Student">
select id,name,age from student
<where>
<!-- and 必须要加上mybatis只会减 不会加 -->
<if test="name!=null and name!=‘‘ ">
and name like concat(‘%‘,#{name},‘%‘)
</if>
<if test="age>0">
and age>#{age}
</if>
</where>
</select>
代码:
<!--动态sql choose
姓名不空 按照姓名查询 年龄不为空 按照年龄查询
只要满足一个when 则其他的when则不会执行!
如果都不满足,则会执行otherwise 也就是没有查询结果
-->
<select id="selectStudentsByChoose" resultType="Student">
select id,name,age from student
<where>
<choose>
<when test="age>0 ">
and age>#{age}
</when>
<when test="name!=null and name!=‘‘ ">
and name like concat(‘%‘,#{name},‘%‘)
</when>
<otherwise>
</otherwise>
</choose>
</where>
</select>
代码:
<select id="selectStudentsByForeachArray" resultType="Student">
<!-- 这就不是动态查询了 而是把参数写成固定的了
select id,name,age from student where id in(1,13,15)
-->
select id,name,age from student
<if test="array.length>0">
where id in
<foreach collection="array" item="myId" open="(" separator="," close=")">
#{myId}
</foreach>
</if>
</select>
代码:
<select id="selectStudentsByForeachList" resultType="Student">
select id,name,age from student
<if test="list.size()>0 ">
where id IN
<foreach collection="list" item="myId" open="(" separator="," close=")">
#{myId}
</foreach>
</if>
</select>
代码:
<select id="selectStudentsByForeachStudent" resultType="Student">
select id,name,age from student
<if test="list.size()>0 ">
where id IN
<foreach collection="list" item="stu" open="(" separator="," close=")">
#{stu.id}
</foreach>
</if>
</select>
代码:
<!-- sql片段的使用 -->
<select id="selectStudentsBySql" resultType="Student">
<!-- 引入sql片段-->
<include refid="selectStudent"/>
<if test="list.size()>0" >
where id IN
<foreach collection="list" item="stu" open="(" separator="," close=")">
#{stu.id}
</foreach>
</if>
</select>
<!-- 如果有需求不查询age了,之前需要在所有的查询中删除age字段,
现在只需要在sql片段中删除即可! -->
<sql id="selectStudent">
select id,name,age from student
</sql>
标签:不为 efi student span rom 删除 sep 数组 hlist
原文地址:http://www.cnblogs.com/lyb0103/p/7538384.html