/*
*作者:呆萌老师
*☑csdn认证讲师
*☑51cto高级讲师
*☑腾讯课堂认证讲师
*☑网易云课堂认证讲师
*☑华为开发者学堂认证讲师
*☑爱奇艺千人名师计划成员
*在这里给大家分享技术、知识和生活
*各种干货,记得关注哦!
*vx:it_daimeng
*/
动态sql:
- If
<select id="getStudentBySname" resultMap="studentMap" parameterType="Student">
select * from student where 1=1
<if test="sname !=null">
and sname=#{sname}
</if>
<if test="age !=0">
and age=#{age}
</if>
</select>
2、Choose
<select id="getStudentByParam"
parameterType="Student" resultType="Student">
SELECT * FROM student WHERE 1=1
<!-- 类似于 swtich 一次进到一个case(when) -->
<choose>
<when test="sname != null">
AND sname = #{sname}
</when>
<when test="age!=0">
AND age=#{age}
</when>
<otherwise>
AND 1=1
</otherwise>
</choose>
</select>
3、Set
<update id="updateStudent"
parameterType="Student">
update Student
<set>
<if test="sname != null">sname=#{sname},</if>
<if test="age != 0">age=#{age},</if>
<if test="grade != null and grade.gid!=0">gid=#{grade.gid},</if>
</set>
where sid=#{sid}
</update>
4、Foreach
Foreach主要用在构建in条件中,它可以在sql语句中进行迭代一个集合。Foreach元素的属性主要有item,index,collection,open,separator,close.
Item表示集合中每一个元素进行迭代时的别名。
index指定一个名字,用于表示在迭代过程中,每次迭代到的位置。
Open表示该语句以什么开始。
Separator表示在每次进行迭代之间以什么符号进行分割
Close表示该语句以什么结束.
Collection属性是必须指定的,但是在不同情况下,该属性的值是不一样的,主要有以下3种情况:
- 如果传入的是单参数且参数类型是一个list的时候,collection中的属性值为list
- 如果传入的是单参数且参数类型是一个array数组的时候,collection的属性值为array
- 如果传入的参数是多个的时候,前面就需要把它们封装成一个map了,当然单参数也可以封装成map,实际上如果你在传入参数的时候,在breast里面也是会把它封装成一个map的,map的key就是参数名,所以这个时候collection的属性值就是传入的list或array对象在自己封装的map里面的key
例1:单参数list的类型
Mapper层代码
<select id="selectStudentBySid" resultType="Student" >
SELECT *
FROM student
WHERE sid in
<foreach item="item" index="index" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
Dao层代码:
public List<Student> selectStudentBySid(List<Integer> list)
{}
封装list代码:
List list=new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
例2:单参数array数组的类型
Mapper层代码
<select id="selectStudentBySid" resultType="Student" >
SELECT *
FROM student
WHERE sid in
<foreach item="item" index="index" collection="array"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
Dao层代码:
public List<Student> selectStudentBySid(int[] list)
{}
例3:将参数封装成map的类型
Mapper层代码
<select id="selectStudentBySid" resultType="Student" >
SELECT *
FROM student
WHERE sname like "%"#{sname}"%" and sid in
<foreach item="item" index="index" collection="sids"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
Collection的值为ids,是传入的参数map的key
Dao层代码:
public List<Student> selectStudentBySid(Map<String, Object> params){ }
测试代码:
List list=new ArrayList<Integer>();
list.add(1);list.add(2);list.add(3);
Map<String,Object> params=new HashMap<String,Object>();
Params.put("sids",list);
Params.put("sname",sname);