<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.java1234.mappers.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
</resultMap>
<select id="searchStudents" parameterType="Map" resultMap="StudentResult">
select * from t_student
where gradeId=#{gradeId} <!-- 或者使用1==1,因为有时候后面所有条件多不存在,也有利于后面第一个and的存在-->
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</select>
<!-- choose when otherwise用在下拉菜单的时候 -->
<select id="searchStudents2" parameterType="Map" resultMap="StudentResult">
select * from t_student
<choose>
<when test="searchBy=='gradeId'">
where gradeId=#{gradeId}
</when>
<when test="searchBy=='name'">
where name like #{name}
</when>
<otherwise>
where age=#{age}
</otherwise>
</choose>
</select>
<select id="searchStudents3" parameterType="Map" resultMap="StudentResult">
select * from t_student
<where> <!--常用 1,自动加上 where;2,如果 where 子句以 and 或者 or 开头,则自动删除第一个 and 或者 or; -->
<if test="gradeId!=null">
gradeId=#{gradeId}
</if>
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</where>
</select>
<select id="searchStudents4" parameterType="Map" resultMap="StudentResult">
select * from t_student
<trim prefix="where" prefixOverrides="and/or"><!-- 功能和 where 元素类似,提供了前缀,后缀功能,更加灵活; -->
<if test="gradeId!=null">
gradeId=#{gradeId}
</if>
<if test="name!=null">
and name like #{name}
</if>
<if test="age!=null">
and age=#{age}
</if>
</trim>
</select>
<select id="searchStudents5" parameterType="Map" resultMap="StudentResult">
select * from t_student
<if test="gradeIds!=null">
<where>
gradeId in
<foreach item="gradeId" collection="gradeIds" open="(" separator="," close=")">
#{gradeId}
</foreach>
</where>
</if>
</select>
<update id="updateStudent" parameterType="Student">
update t_student
<set> <!--常用 1,自动加上 set;2,自动剔除最后一个逗号“,”; -->
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
</set>
where id=#{id}
</update>
</mapper>
具体项目代码:https://download.youkuaiyun.com/download/chpllp/10590733