上面一篇文章中,比如if判断的语句,可以抽取出来组成一个sql片段,方便程序员程序的开发,于是上述的if片段可以定义为如下的sql片段:
<!--sql片段
id:sql片段的唯一标识
经验:一般基于单表地定义sql片段,这样可重用性比较高,sql片段中不要包含 where
第一步:定义sql片段
第二步:引用sql片段
-->
<sql id="select_student">
<if test="student!=null">
<if test="student.sname!=null and student.sname!=''">
and s.sname=#{student.sname}
</if>
<if test="student.ssex!=null and student.ssex!=''">
and s.ssex=#{student.ssex}
</if>
</if>
</sql>
然后引用sql片段如下:
<!--使用if判断条件是否为空,进行查询sql语句的拼接-->
<select id="selectStudentMul" parameterType="com.ajin.mybatis.model.StudentVo" resultType="com.ajin.mybatis.model.Student">
<!-- select * from student where sname=#{student.sname} and ssex =#{student.ssex}
一定要注意上面这句话是否时真的注释成功了,就是满足xml文件注释的格式,否则不小心会发现虽然注释了,但是最终运行会报错,并没有被注释掉
-->
select * from student s
<!-- 使用where标签可以自动去掉第一个and 很方便-->
<where>
<!--
<if test="student!=null">
<if test="student.sname!=null and student.sname!=''">
and s.sname=#{student.sname}
</if>
<if test="student.ssex!=null and student.ssex!=''">
and s.ssex=#{student.ssex}
</if>
</if>
-->
<!-- 引用sql片段的id,引用其它文件中的需要加上namespace-->
<include refid="select_student"></include>
<!-- 在这里还要引用其它的sql片段-->
</where>
</select>
原来的if片段可以看到被注释掉了,换为下面include sql片段的方式:
上面演示了sql片段的一种方式,对于查询出来的列名称,我们也可以使用sql片段的方式如下:
<sql id="Base_Column_List" >
id, name, password
</sql>
然后在查询中引用这三列:
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from userinfo
where id = #{id,jdbcType=INTEGER}
</select>