MyBatis:配置文件完成增删改查_添加

1 实现添加操作

  1. 编写接口方法:Mapper接口
  1. 编写sql语句:sql映射文件
cpp 复制代码
   <insert id="add">

        insert into tb_brand(brand_name,company_name,ordered,description,status)
        values
        (#{brandName},#{companyName},#{ordered},#{description},#{status});

    </insert>
  1. 执行方法,测试

MyBatis事务:

  • openSession():默认开启事务,进行增删改操作后需要使用sqlSession.commit();手动提交事务
  • openSession(true):设置为自动提交事务(关闭事务)
cpp 复制代码
  @Test
    public void testAdd() throws Exception{
        int status = 1;
        String brandName = "波导";
        String companyName = "波导手机";
        String description = "手机中的战斗机";
        int ordered = 100;

        Brand brand = new Brand();
        brand.setStatus(status);
        brand.setBrandName(brandName);
        brand.setCompanyName(brandName);
        brand.setDescription(description);
        brand.setOrdered(ordered);

        // 加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        // 获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();

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

        brandMapper.add(brand);
        sqlSession.commit();
        sqlSession.close();
    }


2 主键返回

在数据添加成功后,需要获取插入数据库数据的主键的值

比如:添加订单和订单项

  1. 添加订单
  2. 添加订单项,订单项中需要设置所属订单的id


解决:

cpp 复制代码
    <insert id="add" useGeneratedKeys="true" keyProperty="id">

        insert into tb_brand(brand_name,company_name,ordered,description,status)
        values
        (#{brandName},#{companyName},#{ordered},#{description},#{status});

    </insert>


相关推荐
徐徐同学8 小时前
cpolar为IT-Tools 解锁公网访问,远程开发再也不卡壳
java·开发语言·分布式
Mr.朱鹏9 小时前
Nginx路由转发案例实战
java·运维·spring boot·nginx·spring·intellij-idea·jetty
白露与泡影10 小时前
2026版Java架构师面试题及答案整理汇总
java·开发语言
历程里程碑11 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
qq_2290580111 小时前
docker中检测进程的内存使用量
java·docker·容器
我真的是大笨蛋11 小时前
InnoDB行级锁解析
java·数据库·sql·mysql·性能优化·数据库开发
钦拆大仁11 小时前
Java设计模式-单例模式
java·单例模式·设计模式
小手cool11 小时前
在保持数组中对应元素(包括负数和正数)各自组内顺序不变的情况下,交换数组中对应的负数和正数元素
java
笨手笨脚の11 小时前
深入理解 Java 虚拟机-04 垃圾收集器
java·jvm·垃圾收集器·垃圾回收
skywalker_1112 小时前
Java中异常
java·开发语言·异常