首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过MYSQL JDBC驱动使用SimpleJdbcInsert和executeBatch获取生成的密钥?

如何通过MYSQL JDBC驱动使用SimpleJdbcInsert和executeBatch获取生成的密钥?
EN

Stack Overflow用户
提问于 2015-02-03 15:39:24
回答 1查看 1.3K关注 0票数 4

我想一次插入多条记录,并获取每条记录的id,这是自动递增的。我是用下面的方法来做的,但是得到的是更新的行数,而不是生成的键,在本例中是id。

代码语言:javascript
复制
public int[] addPersons(List<Person> persons)
{
   SqlParameterSource[] records= new BeanPropertySqlParameterSource[persons.size()] ;

    int i = 0;
    for (Person person: persons) 
   {
         records[i]= new BeanPropertySqlParameterSource(person);
         i++;   
    }

  SimpleJdbcInsert insertPerson=new SimpleJdbcInsert(dsource).withTableName("PersonTable").usingGeneratedKeyColumns("id");
 int [] ids= insertPerson.executeBatch(records);

  return ids;
}

这里的人就是豆子。那么,对于添加的记录,如何获取自动生成的id键呢?

EN

回答 1

Stack Overflow用户

发布于 2015-02-11 19:12:23

当您调用executeBatch方法时,Spring JDBC不允许检索生成的键。这是因为它在内部调用java.sql.PreparedStatementexecuteBatch()方法,该方法只返回受影响的行数。另一种方法是使用executeAndReturnKey方法多次执行insert语句。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28293650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档