当前位置: 首页 > 工具软件 > delete > 使用案例 >

MyBatis入门-delete用法

曹原
2023-12-01

MyBatis中delete用法

本篇内容

  • delete标签基本使用

实践-删除一条记录

mapper

    /**
     * 根据主键删除
     * @param user 用户记录
     * @return 执行得sql影响得行数
     */
    int deleteById(SysUser user);

xml

<!--通过主键删除-->
    <delete id="deleteById">
        delete from mybatis.sys_user where id = #{id}
    </delete>

测试方法:查出一条记录再删除

public void testDeleteById(){
        SqlSession sqlSession = getSqlSession();

        try {
            SysUserMapper mapper = sqlSession.getMapper(SysUserMapper.class);
            //获取数据库中一条记录进行删除
            SysUser user = mapper.queryById(1L);
            Assert.assertNotNull(user);
            LOGGER.info("用户信息:{}",user.toString());

            //删除数据,delete标签方法返回值是执行sql影响的行数
            int result = mapper.deleteById(user);
            Assert.assertEquals(1,result);
            //查看删除后的数据
            SysUser sysUser = mapper.queryById(1L);
            Assert.assertNull(sysUser);
        } finally {
            //为了不影响其他测试,这里进行回滚
            //由于默认的sqlSessionFactory.openSession()是不自动提交的
            //因此不手动执行commit也不会提交到数据库
            sqlSession.rollback();
            //关闭sqlSession
            sqlSession.close();
        }
    }

执行结果,发现经过删除的记录无法再查询出来

==>  Preparing: select id, user_name, user_password, user_email, user_info, head_img, create_time from mybatis.sys_user where id = ? 
==> Parameters: 1(Long)
<==    Columns: id, user_name, user_password, user_email, user_info, head_img, create_time
<==        Row: 1, admin, 123456, admin@mybatis.tk, <<BLOB>>, <<BLOB>>, 2021-01-28 21:57:32.0
<==      Total: 1
用户信息:SysUser{id=1, userName='admin', userPassword='123456', userEmail='admin@mybatis.tk', userInfo='管理员', headImg=null, createTime=Thu Jan 28 21:57:32 CST 2021}
==>  Preparing: delete from mybatis.sys_user where id = ? 
==> Parameters: 1(Long)
<==    Updates: 1
==>  Preparing: select id, user_name, user_password, user_email, user_info, head_img, create_time from mybatis.sys_user where id = ? 
==> Parameters: 1(Long)
<==      Total: 0
 类似资料: