
-首先, 添加mybatis的坐标

create table user(
id int primary key auto_increment,
username varchar(10),
password varchar(10)
);





















使用场景:
(1)当出现重复代码时,例如下面这两个查询都出现了select * from user。那么我们
就可以考虑将其共同部分抽取出来。
<select id="findByCondition" resultType="user" parameterType="user">
select * from user
<where>
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != 0">
and password = #{password}
</if>
</where>
</select>
<select id="findByIds" resultType="user" parameterType="list">
select * from user
<where>
<foreach collection="list" open="id=(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
(2)共同部分的抽取过程:将共同部分的sql语句抽取出来放到<sql></sql>标签里面,然后
再在使用这些共同sql语句的地方配置上<include></include>标签。如下面所示。
<!-- 片段的抽取-->
<sql id="selectUser">select * from user</sql>
<select id="findByCondition" resultType="user" parameterType="user">
<include refid="selectUser"></include>
<where>
<if test="id != 0">
and id = #{id}
</if>
<if test="username != null">
and username = #{username}
</if>
<if test="password != 0">
and password = #{password}
</if>
</where>
</select>
<select id="findByIds" resultType="user" parameterType="list">
<include refid="selectUser"></include>
<where>
<foreach collection="list" open="id=(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>






















