动态修改和动态查询变化不是很大,只是换了一个set标签。简单演示,总共分为
3步骤
一、写接口
//动态修改数据
int modify(Brand brand);
二、写SQL
<!-- 动态修改数据-->
<update id="modify">
update tb_brand
<set>
<if test="status != null ">
status = #{status},
</if>
<if test="companyName != null and companyName != '' ">
company_name = #{companyName},
</if>
<if test="brandName != null and brandName != '' ">
brand_name = #{brandName},
</if>
<if test="description != null and description != '' ">
description = #{description},
</if>
</set>
where id = #{id}
</update>
三、写测试用例
这里就和新增一条数据差不多,无需多言。
@Test
public void testModify() throws IOException {
//1.获取sqlSessionFactort
//①加载mybatis的核心配置文件,获取sqlSessionFatory对象,从官网复制,
String resource = "mybatis-config.xml"; //直接复制配置文件路径,注意是mybatis的
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.
//获取sqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3.
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.
int statue = 1;
String companyName = "修改手机01";
String brandName = "修改手机";
int ordered = 3332;
String description = "modify";
int id = 6;
Brand brand1 = new Brand();
// brand1.setStatus(statue);
brand1.setCompanyName(companyName);
brand1.setBrandName(brandName);
brand1.setDescription(description);
brand1.setOrdered(ordered);
brand1.setId(id);
int modify = mapper.modify(brand1);
System.out.println("修改成功条数: " + modify);
//5.
sqlSession.close();
}
小结一下啊
其实就是一个
set标签
的使用,没有什么复杂的地方。需要注意的地方:
①每一个if语句后面都是一个逗号
,就和多条件查询的and
一样。