一、修改
- 修改全部字段
- 修改动态字段
(一)修改全部字段
- 编写接口方法: Mapper接口 :void update(Brand brand);
- 参数:所有数据
- 结果: void
- 编写SQL语句:SQL映射文件
- 执行方法,测试
1、编写接口方法: Mapper接口
void update(Brand brand);
2、编写SQL语句:SQL映射文件
<update id="update">
update tb_brand
set brand_name = #{brandName},
company_name = #{companyName},
ordered = #{ordered},
description = #{description},
status = #{status}
where id = #{id};
</update>
3、 执行方法,测试
/**
* 添加
*
*/
@Test
public void testUpdate() throws IOException {
//接受参数
int status = 1;
String companyName ="华硕科技有限公司";
String brandName = "华硕手机平板电脑";
int ordered = 56;
String description = "华硕飞行堡垒电脑是你的最佳选择";
int id = 7;
//封装对象
Brand brand = new Brand();
brand.setStatus(status);
brand.setCompanyName(companyName);
brand.setBrandName(brandName);
brand.setOrdered(ordered);
brand.setDescription(description);
brand.setId(id);
//1、加载核心配置文件,获取SqlSessionFactory对象
String resource = "mybatis-config.xml"; //定义配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2、获取SqlSession对象,执行SQL语句
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//3、执行sql
//List<User> users = sqlSession.selectList("test.selectAll");
//3.1 通过SqISession的getMapper方法获取Mapper接口的代理对象
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//3.2 调用对应方法完成sql的执行
brandMapper.update(brand);
//提交事务
//sqlSession.commit();
//4、释放资源
sqlSession.close();
}
缺点:
用户如果只想改其中一个字段,而不输入其他字段的值,那么为输入的属性就会修改成null,非常不灵活。
(二)修改动态字段
用户修改哪个字段是不固定的,那么SQL语句就不能写死,要用动态SQL。结合之前学到的动态SQL
使用if标签和set标签
<update id="update">
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="ordered != null ">
ordered = #{ordered},
</if>
<if test="description != null and description!= ''">
description = #{description}
</if>
</set>
where id = #{id};
</update>