<?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">
<mapper namespace="usernp">
<!--<sql>+<include> 查询user表中id是1的记录 -->
<sql id="columns">
id,name,addr,age
</sql>
<select id="findOne" resultType="User">
select <include refid="columns"/> from user <where> id= #{id}</where>
</select>
<!-- if标签-->
<select id="ifsql" resultType="User">
select <include refid="columns"/> from user
<where>
<if test="id!=0">id=#{id}</if>
<if test="name!=null">and name=#{name}</if>
<if test="addr!=null">and addr=#{addr}</if>
</where>
</select>
</mapper>
相应的测试类
@Test
public void ifSql() {
// 2.创建SQLsession,执行SQL
SqlSession session = ssf.openSession();
// 第一个参数是sql的定位i,第二个是sql的参数值
User user = session.selectOne("usernp.findOne", 1);
// 3.处理结果
System.out.println(user);
// 4.释放资源
session.close();
}