-
在之前的操作之后,若要编写增删改操作,需要变动的只有UserMapper接口,UserMapper.xml以及测试类
-
举例
删除操作-delete:
//Dao层接口UserMapper增加deleteById方法: int deleteById(int id);
映射文件UserMapper.xml中增加与Dao层接口匹配的如下内容
<!--删除操作--> <delete id="deleteById" parameterType="int"> delete from user where id = #{id} </delete>
测试类中的方法
//注意增删改操作都要提交事务!! @Test public void test5() throws IOException { //1. 读取核心配置文件 InputStream in = Resources.getResourceAsStream("mybatis-config.xml"); //2. 创建SqlSessionFactory工厂 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3. 使用工厂生产一个SqlSession对象 SqlSession session = factory.openSession(); //4. 使用SqlSession创建Dao接口的代理对象 UserMapper userMapper = session.getMapper(UserMapper.class); userMapper.deleteById(1); //需要提交事务 session.commit(); //6. 释放资源 session.close(); in.close(); }