18、mybatis學習——mybatis的動態sql之通過{ 結合}或者{ 的結合}實現部分字段更新


Student.java

 StudentMapper接口定義方法

 StudentMapper配置文件進行相應配置

方式一(<set>和<if>結合)

     <update id="updateStu">
         update student
         <!-- set會去掉拼接后的字符串多余的(逗號),
             比如只修改id時則會把id=#{id}后面的(逗號)去掉 -->
         <set>
             <if test="id!=null">
                 id = #{id},
             </if>
             <if test="name!=null &amp;&amp; name.trim()!=''">
                 name = #{name}
             </if>
         </set>
         where id = #{id}
     </update>

方式二(<trim>和<if>結合)

     <update id="updateStu">
         update student
         <!-- 通過trim也能實現去掉拼接后的字符串多余的(逗號) -->
         <trim prefix="set" suffixOverrides=",">
             <if test="id!=null">
                 id = #{id},
             </if>
             <if test="name!=null &amp;&amp; name.trim()!=''">
                 name = #{name}
             </if>
         </trim>
         where id = #{id}
     </update>

測試方法

    //測試動態sql的{<set>和<if>結合}或者{<trim>和<if>的結合}實現部分字段更新
    @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();
    }

原來id為1的數據

 執行測試方法后

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM