目录
如图所示是修改页面,用户在该页面书写需要修改的数据,点击 提交
按钮,就会将数据库中对应的数据进行修改。注意一点,如果哪儿个输入框没有输入内容,我们是将表中数据对应字段值替换为空白还是保留字段之前的值?答案肯定是保留之前的数据。
接下来我们就具体来实现
在 BrandMapper
接口中定义修改方法。
- /**
- * 修改
- */
- void update(Brand brand);
上述方法参数 Brand 就是封装了需要修改的数据,而id肯定是有数据的,这也是和添加方法的区别。
在 BrandMapper.xml
映射配置文件中编写修改数据的 statement
。
- <update id="update">
- update tb_brand
- <set>
- <if test="brandName != null and brandName != ''">
- brand_name = #{brandName},
- if>
- <if test="companyName != null and companyName != ''">
- company_name = #{companyName},
- if>
- <if test="ordered != null">
- ordered = #{ordered},
- if>
- <if test="description != null and description != ''">
- description = #{description},
- if>
- <if test="status != null">
- status = #{status}
- if>
- set>
- where id = #{id};
- update>
set 标签可以用于动态包含需要更新的列,忽略其它不更新的列。
在 test/java
下的 com.itheima.mapper
包下的 MybatisTest类中
定义测试方法
执行测试方法结果如下:
从结果中SQL语句可以看出,只修改了 status
字段值,因为我们给的数据中只给Brand实体对象的 status
属性设置值了。这就是 set
标签的作用。
如上图所示,每行数据后面都有一个 删除
按钮,当用户点击了该按钮,就会将改行数据删除掉。那我们就需要思考,这种删除是根据什么进行删除呢?是通过主键id删除,因为id是表中数据的唯一标识。
接下来就来实现该功能。
在 BrandMapper
接口中定义根据id删除方法。
- <delete id="deleteById">
- delete from tb_brand where id = #{id};
- delete>
在 BrandMapper.xml
映射配置文件中编写删除一行数据的 statement
- <delete id="deleteById">
- delete from tb_brand where id = #{id};
- delete>
在 test/java
下的 com.itheima.mapper
包下的 MybatisTest类中
定义测试方法
- @Test
- public void testDeleteById() throws IOException {
- //接收参数
- int id = 6;
-
- //1. 获取SqlSessionFactory
- String resource = "mybatis-config.xml";
- InputStream inputStream = Resources.getResourceAsStream(resource);
- SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- //2. 获取SqlSession对象
- SqlSession sqlSession = sqlSessionFactory.openSession();
- //SqlSession sqlSession = sqlSessionFactory.openSession(true);
- //3. 获取Mapper接口的代理对象
- BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
- //4. 执行方法
- brandMapper.deleteById(id);
- //提交事务
- sqlSession.commit();
- //5. 释放资源
- sqlSession.close();
- }
运行过程只要没报错,直接到数据库查询数据是否还存在。