修改 IUserMapper
增加deleteById方法
public int deleteById(String id);
解释:
- 形参 String id:传入id,根据id删除
完整代码
package org.malaoshi.mapper;
import org.malaoshi.entity.User;
import java.util.List;
public interface IUserMapper {
public List<User> selectAll();
public int save(User user);
public int updateById(User user);
public int deleteById(String id);
}
修改 userMapper.xml
增加delete标签,根据id修改记录
<delete id="deleteById" >
delete from user where id=#{id}
</delete>
解释:
- 不需要
parameterType属性,因为传入的是java基本数据类型 #{id}:传入的值,此处可以随意起名,因为只传入一个值
完整代码如下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace名字必须与dao包路径接口名完全相同 -->
<mapper namespace="org.malaoshi.mapper.IUserMapper" >
<!-- id名必须与dao中的方法名相同 -->
<select id="selectAll" resultType="org.malaoshi.entity.User">
select id,username,password from user
</select>
<insert id="save" parameterType="org.malaoshi.entity.User">
insert into user (id,username,password) values (#{id},#{username},#{password})
</insert>
<update id="updateById" parameterType="org.malaoshi.entity.User">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<delete id="deleteById" >
delete from user where id=#{id}
</delete>
</mapper>
执行
@Test
public void testDelete() throws IOException {
/*
1. 读取 mybatis-config.xml 自定义命名的全局配置文件.
getResourceAsStream 使用的资源路径
*/
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
// 2. 使用sqlSession的工厂构造器来读入全局配置,再生成一个sqlSession工厂.
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 3. 通过 sqlSession 工厂打开一个 sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//4 使用SqlSession创建Dao接口的代理对象
IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);
int num=mapper.deleteById("1000");
System.out.println("删除 "+num+" 条记录");
//提交事务
sqlSession.commit();
sqlSession.close();
inputStream.close();
}
注意:
执行后要提交事务,否则不会保存到数据库中