← 返回首页
Mybatis基础教程(十)
发表时间:2022-03-07 21:10:36
更新操作

mybatis提供了set元素主要用于更新操作,它可以在动态SQL语句前面输出一个关键字SET,并且可以使用trim去除多余的逗号。

接上小节案例,我们实现根据用户编号更新用户资料。

1.在usersMapper.xml添加更新语句

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.usersMapper">
    <!--更新操作-->
    <update id="updateUserByUid" parameterType="Users">
        update users
        <!--去除最后一个逗号-->
        <trim prefix="set" suffixOverrides=",">
            <!--如果字段不等于NULL,我才更新-->
            <if test="username != null">
                username = #{username},
            </if>
            <if test="password != null ">
                password = #{password},
            </if>
            <if test="mobile != null">
                mobile = #{mobile},
            </if>
            <if test="email != null ">
                email = #{email},
            </if>
            <if test="type != null">
                type = #{type},
            </if>
        </trim>
        where  uid = #{uid}
    </update>
</mapper>

2.编写测试类

    @Test
    public void testUpdateUserByUid(){
        SqlSession session = null;
        Users u = null;

        try {
            session = SqlSessionFactoryUtil.openSqlSession();
            u = session.selectOne("getUser",4);
            //System.out.println(u);
            u.setPassword("888888");
            u.setMobile("18991989999");
            u.setType(""); //空字段不会被更新
            session.update("updateUserByUid",u);
            session.commit();
        } catch (Exception ex) {
            ex.printStackTrace();
            session.rollback();
            session.commit();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }