Mybatis基础环境准备请看:Mybatis基础环境准备
本篇讲解Mybati数据CRUD数据操作之单条删除数据
当用户点击了该按钮,就会将改行数据删除掉。那我们就需要思考,这种删除是根据什么进行删除呢?是通过主键id删除,因为id是表中数据的唯一标识。
1,编写接口方法
在 com.itheima.mapper
包写创建名为 BrandMapper
的接口。在 BrandMapper
接口中定义uodate方法。
/**
* 根据id删除
*/
void deleteById(int id);
2,编写SQL语句
在 reources
下创建 com/itheima/mapper
目录结构,并在该目录下创建名为 BrandMapper.xml
的映射配置文件,
<delete id="deleteById">
delete from tb_brand where id = #{id};
</delete>
3,编写测试方法
在 test/java
下的 com.itheima.mapper
包下的 MybatisTest类中
定义测试方法
@Test
public void testDeleteById() throws IOException {
//接收参数
int id = 4;
//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();
}
执行测试方法结果如下:
查询数据库发现已经把id为4的记录删除了:
[声明]:内容主要来源黑马程序员网上资源学习