目标
- 能够使用映射配置文件实现CRUD操作
- 能够使用注解实现CRUD操作

如上图所示,每行数据后面都有一个 删除 按钮,当用户点击了该按钮,就会将改行数据删除掉。那我们就需要思考,这种删除是根据什么进行删除呢?是通过主键id删除,因为id是表中数据的唯一标识。
接下来就来实现该功能。
在 BrandMapper 接口中定义根据id删除方法。
xxxxxxxxxx
/** * 根据id删除 */void deleteById(int id);
在 BrandMapper.xml 映射配置文件中编写删除一行数据的 statement
xxxxxxxxxx
<delete id="deleteById"> delete from tb_brand where id = #{id};</delete>
在 test/java 下的 com.itheima.mapper 包下的 MybatisTest类中 定义测试方法
xxxxxxxxxx
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();}
运行过程只要没报错,直接到数据库查询数据是否还存在。