MyBatis 3 批量插入返主键官方已经修复

本文介绍了一个使用MyBatis进行批量数据插入的例子,并展示了如何确保每条记录的ID自动生成。通过一个具体的单元测试案例,演示了如何创建并插入包含多个国家信息的数据列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

164349_c1fM_86738.png

 

<?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">
<mapper namespace="org.apache.ibatis.executor.keygen.CountryMapper" >
  <insert id="insertList" parameterType="org.apache.ibatis.executor.keygen.Country" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
      insert into country (countryname,countrycode)
      values
      <foreach collection="list" separator="," item="country">
          (#{country.countryname},#{country.countrycode})
      </foreach>
  </insert>
</mapper>

 

@Test
  public void shouldInsertListAndRetrieveId() throws Exception {
    Reader reader = Resources.getResourceAsReader("org/apache/ibatis/executor/keygen/MapperConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
      CountryMapper mapper = sqlSession.getMapper(CountryMapper.class);
      List<Country> countries = new ArrayList<Country>();
      countries.add(new Country("China", "CN"));
      countries.add(new Country("United Kiongdom", "GB"));
      countries.add(new Country("United States of America", "US"));
      mapper.insertList(countries);
      for (Country country : countries) {
        assertNotNull(country.getId());
      }
    } finally {
      sqlSession.rollback();
      sqlSession.close();
    }
  }

具体修复参见:https://github.com/mybatis/mybatis-3/pull/547
相关参考文章:https://my.oschina.net/zudajun/blog/674946

转载于:https://my.oschina.net/wenjinglian/blog/813879

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值