<where>
<if test="id!=0 and id!=null">id=#{id}</if>
<if test="name!=null">and name=#{name}</if>
<if test="addr!=null">and addr=#{addr}</if>
</where>
<where></where>标签 在参数不足时会自动去掉 and
<?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>
</mapper>
对应的测试方法
package test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import pojo.User;
/**
* 这个类用来测试动态sql拼接
*
* @author Administrator
*
*/
public class DynamicSqlTest {
SqlSessionFactory ssf = null;
@Before
public void init() {
// 1.创建会话工厂
try {
InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml");
ssf = new SqlSessionFactoryBuilder().build(in);
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void findOne() {
// 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();
}
}