★学习目标:
掌握Mybatis的更新操作,能够在代码中进行熟练使用<set>元素进行更新
★思考任务:
MyBatis中的<set>元素的作用是什么?
★任务学习:
★知识要点:
<set>元素使用场景
在Hibernate框架中,如果想要更新某一个对象,就需要发送所有的字段给持久化对象,然而在实际应用中,大多数情况下都是更新某一个或几个字段。如果更新的每一条数据都要将其所有的属性都更新一遍,那么执行效率是非常差的。为了解决更新数据的效率问题,MyBatis提供了<set>元素。<set>元素主要用于更新操作,它可以在动态SQL语句前输出一个SET关键字,并将SQL语句中最后一个多余的逗号去除。<set>元素与<if>元素结合可以只更新需要更新的字段。
通过一个案例演示如何使用<set>元素更新数据库的信息,案例具体步骤如下。在映射文件CustomerMapper.xml中,添加使用<set>元素执行更新操作的动态SQL。
<update id="updateCustomerBySet" parameterType="com.itheima.pojo.Customer">update t_customer
<set>
<if test="username !=null and username !=''">
username=#{username},</if>
<if test="jobs !=null and jobs !=''"> jobs=#{jobs},</if>
<if test="phone !=null and phone !=''">phone=#{phone},</if>
</set> where id=#{id}
</update>
编写测试方法updateCustomerBySetTest()。
public void updateCustomerBySetTest() {
SqlSession sqlSession = MyBatisUtils.getSession();
Customer customer = new Customer(); customer.setId(3);
customer.setPhone("13311111234");
int rows = sqlSession.update("com.itheima.mapper"
+ ".CustomerMapper.updateCustomerBySet", customer);
if(rows > 0) {System.out.println("您成功修改了"+rows+"条数据!");
} else { System.out.println("执行修改操作失败!!!");
}sqlSession.commit();sqlSession.close();
}
<set>元素字段非空
在映射文件中使用<set>元素和<if>元素组合进行update语句动态SQL组装时,如果<set>元素内包含的内容都为空,则会出现SQL语法错误。因此,在使用<set>元素进行字段信息更新时,要确保传入的更新字段不能都为空。

