MyBatis添加功能

发布时间 2023-03-29 11:16:43作者: YE-

添加

  • 编写接口方法:Mapper接口
    • 参数:除了id之外的所有数据
    • 结果:viod
  • 编写SQL语句:SQL映射文件
  • 执行方法,测试
    • MyBatis事务:
    • openSession():默认开启事务,进行增删改查操作后需要使用sqlSession。commot(); 手动提交事务
    • openSession(true):可以设置为自动提交事务(关闭事务)

 步骤一:写类名

 

 

 步骤二:书写SQL类名

 

 

 步骤三:测试类测试

//添加数据
     public void testAdd() throws IOException {
         //接受参数
         //现在是固定数据,以后会变成动态数据
         int id = 4;
         String brandName = "8848钛合金手机,尊贵";
         String companyName = "8848";
         String ordered = "100";
         String description = "人机分离十米自动爆炸";
         int status = 1;

         //处理参数,定义一个关键字,将查询的关键字封装
         Brand brand = new Brand();
         brand.setId(id);
         brand.setBrandName(brandName);
         brand.setCompanyName(companyName);
         brand.setOrdered(ordered);
         brand.setDescription(description);
         brand.setStatus(status);


         //1. 获取SqlSessionFactory
         String resource = "mybatis-config.xml";
         InputStream inputStream = Resources.getResourceAsStream(resource);
         SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
         //2.获取Sqlsession对象
         SqlSession sqlSession = sqlSessionFactory.openSession();

         //3.获取Mapper接口的代理对象
         BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

         //4.执行方法
         brandMapper.add(brand);

         //5.释放资源
         sqlSession.close();
     }

需要修改这三处

1.接收全部参数

 

 2.全部参数进行封装

 

 3.执行方法,不需要输出