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


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

     执行测试方法后

     

  • 相关阅读:
    python基础学习4(内置函数)
    python基础学习5(包与模块)
    放弃用你的InnerHTML来输出HTML吧,jQuery Tmpl不详细讲解
    Entity Framework 4.1 CodeFirst实例
    .net企业库数据处理模块使用DAAB来开发应用
    行转列和列转行
    读懂这100这句话,你会懂得很多
    iis 6 下有关gzip 的有关配置
    jquery 设置 Select CheckBox Radio
    SQL函数说明大全
  • 原文地址:https://www.cnblogs.com/lyh233/p/12359715.html
Copyright © 2020-2023  润新知