MyBatis set 标签

set 标签可以被用于动态包含需要更新的列,而舍去其他的,例如多余的逗号。

<!-- 根据id查询员工信息-->
<select id="selectEmployeewithId" parameterType="int" resultType="cn.mybatis.domain.Employee">
    SELECT * FROM tb_employee where id = #{id}
</select>

<!-- 动态更新员工信息-->
<update id="updateEmployeeIfNecessary" parameterType="cn.mybatis.domain.Employee">
    update tb_employee
    <set>
      <if test="loginname != null">loginname=#{loginname} ,</if>
      <if test="password != null">password=#{password} ,</if>
      <if test="name != null">name=#{name},</if>
      <if test="sex != null">sex=#{sex},</if>
      <if test="age != null">age=#{age},</if>
      <if test="phone != null">phone=#{phone} ,</if>
      <if test="sal != null">sal=#{sal},</if>
      <if test="state != null">state=#{state}</if>
    </set>
    where id=#{id}
</update>

set 标签会动态前置SET关键字,同时也会消除无关的逗号,因为使用了条件语句之后很可能就会在生成的赋值语句的后面留下这些逗号。

// 根据id查询员工
Employee selectEmployeeWithId(Integer id);
// 动态更新员工
void updateEmployeeIfNecessary (Employee employee);

需要注意的是,updateEmployeelfNecessar方法传递的参数不是之前使用的HashMap,而是一个Employee对象,因为通常更新操作时都是先查询出一个实体对象再进行更新操作。

public void testUpdateEmployeeIfNecessary(qlSession session)
{
    EmployeeMapper em = session.getMapper(EmployeeMapper.class);
    // 查询id为4的员工信息
    Employee employee = em.selectEmployeewithId(4);
    // 设置需要修改的属性
    employee.setLoginname("mary");
    employee.setPassword("123");
    employee.setName("玛丽");
    em.updateEmployeeIfNecessary(employee);
}

测试updateEmployeelfNecessa方法,控制台显示如下:

DEBUG [main]==> Preparing: SELECT * FROM tb_ employee where id= ?
DEBUG [main]==> Parameters :4 (Integer)
DEBUG [main]<== Total :1
DEBUG [main]==> Preparing :update tb_employee SET loginname=?,password=?,name=?,sex=?,age=?,phone=?,sal=?,state=? where id=?
DEBUG [main]==> Parameters: mary(String),123(String),玛丽(String),女(String),20(Integer),13902016666(String),5800.0(Double),ACTIVE(String),4 (Integer)
DEBUG [main]<== Updates :1

可以看到,首先执行了一条查询语句,查询id为4的员工,之后执行了一条update语句,根据传入的Employee对象更新员工信息。切换到数据库,可以看到id为4的员工信息已经更新。

标签: none

[网站公告]-[2024年兼职介绍]


添加新评论