代码片段
sql标签用于定义SQL片段,可以在其他标签中使用<include/>子标签引用该片段,
<sql id="sqlid">select * from student</sql>
<select id="selectForeach" resultType="Student">
<include refid="sqlid" /> where id in
<foreach collection="list" item="student" open="(" close=")" separator=",">
#{student.id}
</foreach>
</select>
动态sql
动态sql: sql的内容是变化的,可以根据条件获取到不同的sql语句。主要是where部分发生变化
动态sql的实现: 使用的是mybatis提供的标签,<if>,<where>,<foreach>
<if>和<where>
<if>是判断条件的
语法<if test=“判断java对象的属性值”></if>
<!--动态sql,使用if标签,标签中判断为真,将语句加到sql的where后面,
where会自动将if中的多余的and or去掉 -->
<select id="selectStudentIf" resultType="Student">
select id,name,age,email from student
<where>
<if test="name !=null and name !=''">
name=#{name}
</if>
<if test="age>0">
or age > #{age}
</if>
</where>
</select>
<foreach>
循环java中的数组,list集合的。主要用在sql语句的in中。
例如
select * from student where id in (1,2,3,4)
public List<Student> selectFor(List<Integetr> idlist)
<!-- foreach标签
collection写参数的类型,数组使用array,如果是List集合使用list
item自定义表示数组和集合成员的变量,要写进括号里的变量
open循环开始时的字符
close循环结束时的字符
separator集合成员之间的分隔符
-->
<select id="selectForeach" resultType="Student">
<include refid="sqlid" /> where id in
<foreach collection="list" item="myid" open="(" close=")" separator=",">
#{myid}
</foreach>
</select>
如果传的是对象,可以访问其属性
括号也可以拼接在外面
<select id="selectForeach" resultType="Student">
<include refid="sqlid" /> where id in (
<foreach collection="list" item="student" separator=",">
#{student.id}
</foreach>
)
</select>