18, mybatis learning - by {<set> and <if> binding} or {<trim> and <if> binding to achieve some field update}

Student.java

 

 StudentMapper interface defines the methods

 

 StudentMapper profile configured accordingly

A manner (<set> and <if> binding)

     <update id="updateStu">
         update student
         <-! SET will remove extra string (comma) after the splicing,
             The example will id = # {id} later (comma) is modified to remove only the ID -> 
         < SET > 
             < IF Test = "null ID =!" >
                 id = #{id},
             </if>
             <if test="name!=null &amp;&amp; name.trim()!=''">
                 name = #{name}
             </if>
         </set>
         where id = #{id}
     </update>

Second way (<trim> and <if> binding)

     <update id="updateStu">
         update student
         <! - can be achieved by a trim excess string removed after stitching (comma) -> 
         < trim prefix = "SET" suffixOverrides = "," > 
             < IF Test = "null ID =!" >
                 id = #{id},
             </if>
             <if test="name!=null &amp;&amp; name.trim()!=''">
                 name = #{name}
             </if>
         </trim>
         where id = #{id}
     </update>

Test Methods

    // testing of dynamic sql {<set> and <if> binding} or {<trim> and <if> binding update} to achieve some fields 
    @Test
     public  void testUpdateStu () throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        Student student = studentMapper.updateStu(new Student(1, "小王"));
        System.out.println(student);
        sqlSession.close();
    }

The original data id 1

 

 After performing the test method

 

 

 

Guess you like

Origin www.cnblogs.com/lyh233/p/12359715.html