首页 > 其他 > 详细

18、mybatis学习——通过{<set>和<if>结合}或者{<trim>和<if>的结合}实现部分字段更新

时间:2020-02-25 01:19:25      阅读:86      评论:0      收藏:0      [点我收藏+]

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的数据

技术分享图片

 

 执行测试方法后

技术分享图片

 

 技术分享图片

 

18、mybatis学习——通过{<set>和<if>结合}或者{<trim>和<if>的结合}实现部分字段更新

原文:https://www.cnblogs.com/lyh233/p/12359715.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!