MyBatis learning summary (5): MyBatis dynamic sql <if>, <choose>, <where>, <set>, <trim> tags

1. <if> tag

The <if> element in MyBatis is similar to the if statement in Java. The test attribute in the <if> tag is the expression for judgment. There are two points to note:

Use the letter and instead of the ampersand in the expression

String judgment double quotation mark set single quotation mark use

Example: Find information about students who are older than 30 or whose address is in Beijing.

(1) Add a method under IStudentDao.

    List<Student> findByCondition(Student student);

(2) Add a mapping statement in studentMapper.xml.

<select id="findByCondition" parameterType="com.day1.entity.Student" resultType="com.day1.entity.Student">
        select * from t_student where 1=1
        <if test="age > 0">
         and age > #{age}
        </if>
        <if test="address != null and address != ''">
            or address = #{address}
        </if>
    </select>

Note: In the above query statement, 1=1 is added after where to prevent errors in the sql statement. If there is no 1=1, when age and address are empty, the sql statement will become select * from t_student where, and such a statement is wrong.

(3) Add test method.

    @Test
    public void testFindByCondition() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setAge(30);
        student.setAddress("北京");
        List<Student> students = studentDao.findByCondition(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

2、choose、when、otherwise标签

The choose tag is to determine whether the test conditions in the internal when tag are established in order. If one of them is established, choose ends. When all the when conditions in choose are not satisfied, the sql in otherwise is executed. Similar to the switch statement in Java, choose is switch, when is case, and otherwise is default. Its basic structure is as follows:

<!--使用choose、when、otherwise元素根据条件动态查询用户信息-->
<select id="selectStudent" resultType="com.day1.entity.Student" parameterType= "com.day1.entity.Student">
    select * from user where 1=1
    <choose>
        <when test="条件1">
            ...
        </when>
        <when test="条件1">
            ...
        </when>
        <otherwise>
            ...
        </otherwise>
    </choose>
</select>

Example: Find a student whose name starts with Zhang and whose address is in Beijing in the database table. 

(1) Add a method under IStudentDao.

    List<Student> getStudentByChoose(Student student);

(2) Add a mapping statement in studentMapper.xml.

<select id="getStudentByChoose" parameterType="com.day1.entity.Student" resultType="com.day1.entity.Student">
        select * from t_student where
        <choose>
            <when test="username != null and username != ''">
               username like #{username}
            </when>
            <when test="address != null and address != ''">
                and address = #{address}
            </when>
            <otherwise>

            </otherwise>
        </choose>

    </select>

(3) Add test method.

    @Test
    public void testFindByChoose() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setUsername("张%");
        student.setAddress("北京");
        List<Student> students = studentDao.getStudentByChoose(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

3. The <where> element

The function of the <where> element is to output a where statement where the <where> element is written. In addition, there is no need to consider what the conditional output in the <where> element looks like, MyBatis will handle it intelligently. If all the conditions are not met, MyBatis will find out all the records. If the output starts with and, MyBatis will ignore the first and. If it starts with or, MyBatis will ignore it, and there is no need to consider the issue of spaces in the <where> element, and MyBatis will add it intelligently.

Example: Find information about students whose name is Qi Fei, whose age is greater than 30, and whose address is in Hebei.

(1) Add a method under IStudentDao.

    List<Student> getStudentUseWhere(Student student);

(2) Add a mapping statement in studentMapper.xml.

<select id="getStudentUseWhere" resultType="com.day1.entity.Student">
        SELECT * FROM t_student
        <where>
            <if test="username != null">
                username = #{username}
            </if>
            <if test="age > 0">
                AND age > #{age}
            </if>
            <if test="address != null ">
                AND address like #{address}
            </if>
        </where>
    </select>

(3) Add test method.

    @Test
    public void testFindByWhere() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setUsername("齐菲");
        student.setAge(30);
        student.setAddress("河北");
        List<Student> students = studentDao.getStudentUseWhere(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

4. <trim> element

The main function of the <trim> element is to add some prefixes before or after the content it contains. The corresponding attributes are prefix and suffix. It can overwrite some content at the beginning of the included content, that is, ignore, or overwrite some content at the end. The corresponding attributes are prefixOverrides and suffixOverrides. Just because the <trim> element has such a function, it is also very easy to use <trim> to replace the function of the <where> element.

Example: Find the student whose name starts with Liu, and the address is Beijing

(1) Add a method under IStudentDao.

    List<Student> getStudentByTrim(Student student);

(2) Add a mapping statement in studentMapper.xml.

<!--使用trim元素根据条件动态查询用户信息-->
    <select id="getStudentByTrim" resultType="com.day1.entity.Student" parameterType="com.day1.entity.Student">
        select * from t_student
        <trim prefix="where" prefixOverrides = "and | or">
            <if test="username!=null and username!=''">
                and username like #{username}
            </if>
            <if test="address!=null and address!=''">
                and address=#{address}
            </if>
        </trim>
    </select>

(3) Add test method.

    @Test
    public void testFindByTrim() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setUsername("刘%");
        student.setAddress("北京");
        List<Student> students = studentDao.getStudentByTrim(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

5. <set> element

The <set> element can dynamically update the column in the dynamic update statement. 

Example: Modify Wang Ke's address to Zhejiang.

(1) Add a method under IStudentDao.

    int updateStudent(Student student);

(2) Add a mapping statement in studentMapper.xml.

<update id="updateStudent">
        update t_student
        <set>
            <if test="address != null">
            address = #{address}
            </if>
        </set>
        where username = #{username}
    </update>

(3) Add test method.

    @Test
    public void testFindBySet() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setUsername("王可");
        student.setAddress("浙江");
        int sum = studentDao.updateStudent(student);
        System.out.println("修改了" + sum + "记录");
        //6、释放资源
        sqlSession.close();
        in.close();
    }

6. Summary of errors

报错信息:Mapper method 'com.day1.dao.IStudentDao.updateStudent attempted to return null from a method with a primitive return type (int).

Wrong wording:

<select id="updateStudent" resultType="int">
        update t_student
        <set>
            <if test="address != null">
            address = #{address}
            </if>
        </set>
        where username = #{username}
    </select>
    <select id="updateStudent">
        update t_student
        <set>
            <if test="address != null">
            address = #{address}
            </if>
        </set>
        where username = #{username}
    </select>

 Correct writing:

<update id="updateStudent">
        update t_student
        <set>
            <if test="address != null">
            address = #{address}
            </if>
        </set>
        where username = #{username}
    </update>

 

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113822251