这篇文章讲一下sql片段。
讲一下sql片段的的需求:
将上边实现的动态sql判断代码块抽取出来,组成一个sql片段。其它的statement中就可以引用sql片段。
方便程序员进行开发。
第一步我们先定义一个sql片段;
第二步:我们再引用这个sql片段。
这个案例中我们只修改userMapper.xml的代码(其他代码都不用修改),如下:
<?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"> <!-- nanmespace:命名空间。 作用就是对sql进行分类话管理,理解Sal分离 注意:使用mapper代理方式,namespace有特殊重要的作用 --> <mapper namespace="cn.itcast.mybatis.mapper.userMapper"> <!-- 这里的id要和Mapp接口里面的函数名字一模一样。parameterType表示输入的类型, resultType表示输出的类型 --> <select id="findUserList" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultType="cn.itcast.mybatis.po.UserCustom"> SELECT id ,username FROM USER WHERE user.sex= #{userCustom.sex} AND user.username=#{userCustom.username} </select> <!-- 定义resultMap 将SELECT id id_,username username_ FROM USER 和User类中的属性做一个映射关系 type:resultMap最终映射的java对象类型,可以使用别名 id:对resultMap的唯一标识。 --> <resultMap type="user" id="userResultMap"> <!-- id:表示查询结果集中唯一的标识。 column:查询出来的列名 property:type指定的pojo类型中的属性名 最终resultMap对column和property作一个映射关系(对应关系) --> <id column="id_" property="id"/> <result column="username_" property="username"/> </resultMap> <!-- 定义一个sql片段 id:sql片段的唯一标识; 经验:是基于单表来定义sql片段,这样的话这个sql片段可重用性才高 在sql片段中不要包括where --> <sql id="query_user_where"> <if test="userCustom!=null"> <if test="userCustom.sex!=null and userCustom.sex!=''"> and user.sex= #{userCustom.sex} </if> <if test="userCustom.username!=null and userCustom.username!=''" > and user.username=#{userCustom.username} </if> </if> </sql> <select id="findUserByResultMap" parameterType="cn.itcast.mybatis.po.UserQueryVo" resultMap="userResultMap"> SELECT id id_,username username_ FROM USER <!-- where可以自动去掉条件中的第一个and --> <where> <!-- 引用一个sql片段 --> <include refid="query_user_where"></include> </where> </select> </mapper>