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 && 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 && 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的數據
執行測試方法后