.1)if和where标签的使用
1.第一种方式来来实现动态的sql
<!-- 是用if标签实现动态sql语句 1-->
<select id="queryAllStudentByNameAndAgeSql" resultType="student" parameterType="student">
select stuno,stuname,stusex from student where 1=1
<if test="stuSex!=null and stuSex!=''">
and stusex=#{stuSex}
</if>
<if test="stuName!=null and stuName!=''">
and stuname=#{stuName}
</if>
2.第二种方式来实现动态sql方式
<select id="queryAllStudentByNameAndAgeSql" resultType="student" parameterType="student">
select stuno,stuname,stusex from student
<where>
<if test="stuSex!=null and stuSex!=''">
and stusex=#{stuSex}
</if>
<if test="stuName!=null and stuName!=''">
and stuname=#{stuName}
</if>
</where>
</select>
where:标签可以自动的处理第一个and 但是不会处理其他的and 推荐使用第二种方式
.2)foreach标签的使用
1.
如果是类中的集合以下代码就是实例
<!-- 通过年纪实体里里面的所有学号来查询学生-->
<select id="querystuNosInGrade" parameterType="grade" resultType="student">
select * from student
<where>
<if test="nos!=null and nos.size>0">
<foreach collection="nos" open="and stuno in(" close=")" item="no" separator=",">
#{no}
</foreach>
</if>
</where>
</select>
1.1.collection:代表的是要浏览哪个集合
1.2.open 在循环值的前半部分的条件sql语句
1.3 close 在循环值的后半部分的条件sql语句
1.4 item 临时变量 列如一堆学生 这个就代表其中一个
1.5 separator 按照什么样的字符分割数据 列如:-,:, ,
1.6 取值方式:#{临时变量}
2.如果是简单数组类型:无论编写代码时,传递的是什么参数名,在mapper.xml中 必须使用array来代替该数组
<!-- 通过年纪实体里里面的所有学号来查询学生-->
<select id="querystuNosInArray" parameterType="int[]" resultType="student">
select * from student
<where>
<if test="array!=null and array.length>0">
<foreach collection="array" open="and stuno in(" close=")" item="no" separator=",">
#{no}
</foreach>
</if>
</where>
</select>
3.如果是集合类型:无论编写代码时,传递的是什么参数名,在mapper.xml中 必须使用list来代替该集合
<select id="querystuNosInList" parameterType="list" resultType="student">
select * from student
<where>
<if test="list!=null and list.size>0">
<foreach collection="list" open="and stuno in(" close=")" item="no" separator=",">
#{no}
</foreach>
</if>
</where>
</select>
4.如果是对象数组类型的:第一点-----传递值的时候必须是Object[]数组 ,第二点----在取值的时候需要用 临时变量.具体的属性名称
<select id="querystuNosInsObject" parameterType="Object[]" resultType="student">
select * from student
<where>
<if test="array!=null and array.length>0">
<foreach collection="array" open="and stuno in(" close=")" item="student" separator=",">
#{student.stuNo}
</foreach>
</if>
</where>
</select>
.3)SQL片段
1.java中的方法
2.数据库中的存储过程和存储函数
3.mybatis中的sql片段 mybatis怎么提取公共的sql语句呢
<sql id="foreachNo">
<where>
<if test="array!=null and array.length>0">
<foreach collection="array" open="and stuno in(" close=")" item="student" separator=",">
#{student.stuNo}
</foreach>
</if>
</where>
</sql>
<select id="querystuNosInsObject" parameterType="Object" resultType="student">
select * from student
<include refid="foreachNo"></include>
</select>
3.1 使用sql标签来创建片段的部分 再用include的refid的映射导入
来源:https://www.cnblogs.com/thisHBZ/p/12457839.html