动态SQL是MyBatis的强大之处,下面一一学习
一、if语句
在MyBatis中<if>元素时最常用到的判断元素,它类似于Java中的if
1.创建chapter08项目,并将chapter06(chaoter06点这里)中的项目文件复制过来
2.修改映射文件CustomerMapper.xml,并使用if元素进行查询
<?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="com.itheima.mapper.CustomerMapper">
<select id="findCustomerByNameAndJobs" parameterType="Integer" resultType="com.itheima.po.Customer">
select * from t_customer where 1=1
<if test="username!=null and username !='' ">
and username like concat('%',#{username},'%')
</if>
<if test="jobs!=null and jobs!='' ">
and jobs #{jobs}
</if>
</select>
</mapper>
3.在测试类MybatisTest中编写测试方法findCustomerByNameAndJobsTest(),如下所示: