对于该标签的执行,当 test 的值为 true 时,会将其包含的 SQL 片断拼接到其所在的 SQL 语句中。

    语法: sql 语句的部分
    注意:
    标签的中存在一个比较麻烦的地方:需要在 where 后手工添加 1=1 的子句。因为,若 where 后的所有条件均为 false,而 where 后若又没有 1=1 子句,则 SQL 中就会只剩下一个空的 where,SQL出错。所以,在 where 后,需要添加永为真子句 1=1,以防止这种情况的发生。但当数据量很大时,会严重影响查询效率。

    接口方法:**

    1. package com.wzy.dao2;
    2. import com.wzy.pojo.Student;
    3. import org.apache.ibatis.annotations.Param;
    4. import java.util.List;
    5. public interface StudentDao2 {
    6. public abstract List<Student> selectStudentIf(Student student);
    7. }

    mapper 文件:

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <!DOCTYPE mapper
    3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    5. <mapper namespace="com.wzy.dao2.StudentDao2">
    6. <select id="selectStudentIf" resultType="com.wzy.pojo.Student">
    7. select id,name,gender,age,birthday,files from student where 1=1
    8. <if test="name != null and name != ''">
    9. and name = #{name}
    10. </if>
    11. <if test="age > 0">
    12. and age &gt; #{age}
    13. </if>
    14. </select>
    15. </mapper>

    测试方法:

    1. package com.wzy.dao2;
    2. import com.wzy.pojo.Student;
    3. import org.apache.ibatis.io.Resources;
    4. import org.apache.ibatis.session.SqlSession;
    5. import org.apache.ibatis.session.SqlSessionFactory;
    6. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    7. import org.junit.Test;
    8. import java.io.IOException;
    9. import java.io.InputStream;
    10. import java.util.List;
    11. import static org.junit.Assert.*;
    12. public class StudentDao2Test001 {
    13. @Test
    14. public void selectStudentIf() throws IOException {
    15. String config = "MyBatis2.xml";
    16. InputStream resourceAsStream = Resources.getResourceAsStream(config);
    17. SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(resourceAsStream);
    18. StudentDao2 studentDao2 = factory.openSession().getMapper(StudentDao2.class);
    19. Student student = new Student();
    20. student.setName("张三");
    21. student.setId(1);
    22. List<Student> studentList = studentDao2.selectStudentIf(student);
    23. studentList.forEach(student1 -> System.out.println(student1));
    24. }
    25. }