mybatis sql片段(<sql>)

提出问题

在下面的mapper.xml中,sql中有通用部分,如下:

<select id="selectByUsername" resultType="USER">
    select id,username,password from user where username like #{username}
</select>

    <select id="selectById" resultType="USER">
    select id,username,password from user where id=#{username}
</select>

 <select id="select" resultType="USER">
    select id,username,password from user where username=#{username} and password=#{password}
</select>

其中 select id,username,password 出现了3次,如果在 user 表中增加一个字段 birthday ,就要在上面3个sql都要加上该字段

尤其 sql语句复杂,字段较多、或者 有n个查询条件且出现多次重复时,这样操作非常麻烦

解决问题

使用 <sql> 标签,可以将共用的部分抽取出来

修改 userMapper.xml

<!-- 将公共的部分抽取出来 -->
<sql id="selectColumn">
    select id,username,password
</sql>

<select id="selectByUsername" resultType="USER">
    <!-- 使用公共部分 -->
    <include refid="selectColumn"></include>
     from user where username like #{username}
</select>

<select id="selectById" resultType="USER">
    <!-- 使用公共部分 -->
    <include refid="selectColumn"></include>
    from user where id=#{username}
</select>

<select id="select" resultType="USER">
    <!-- 使用公共部分 -->
     <include refid="selectColumn"></include> 
     from user where username=#{username} and password=#{password}
</select>

何时体现优势: sql语句复杂,字段较多、或者 有n个查询条件且出现多次重复时,采用 <sql> 才能体现出优势


原文出处:/show_1EF6aCcoMAOi.html