对于该标签的执行,当 test 的值为 true 时,会将其包含的 SQL 片断拼接到其所在的 SQL 语句中。
语法:
注意:
标签的中存在一个比较麻烦的地方:需要在 where 后手工添加 1=1 的子句。因为,若 where 后的所有条件均为 false,而 where 后若又没有 1=1 子句,则 SQL 中就会只剩下一个空的 where,SQL出错。所以,在 where 后,需要添加永为真子句 1=1,以防止这种情况的发生。但当数据量很大时,会严重影响查询效率。
接口方法:**
package com.wzy.dao2;import com.wzy.pojo.Student;import org.apache.ibatis.annotations.Param;import java.util.List;public interface StudentDao2 {public abstract List<Student> selectStudentIf(Student student);}
mapper 文件:
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.wzy.dao2.StudentDao2"><select id="selectStudentIf" resultType="com.wzy.pojo.Student">select id,name,gender,age,birthday,files from student where 1=1<if test="name != null and name != ''">and name = #{name}</if><if test="age > 0">and age > #{age}</if></select></mapper>
测试方法:
package com.wzy.dao2;import com.wzy.pojo.Student;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.Test;import java.io.IOException;import java.io.InputStream;import java.util.List;import static org.junit.Assert.*;public class StudentDao2Test001 {@Testpublic void selectStudentIf() throws IOException {String config = "MyBatis2.xml";InputStream resourceAsStream = Resources.getResourceAsStream(config);SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);StudentDao2 studentDao2 = factory.openSession().getMapper(StudentDao2.class);Student student = new Student();student.setName("张三");student.setId(1);List<Student> studentList = studentDao2.selectStudentIf(student);studentList.forEach(student1 -> System.out.println(student1));}}
