【问题标题】:How to get generated keys using SimpleJdbcInsert and executeBatch with MYSQL JDBC driver?如何使用 SimpleJdbcInsert 和 executeBatch 和 MYSQL JDBC 驱动程序获取生成的密钥?
【发布时间】:2015-04-02 08:07:03
【问题描述】:

我想一次插入多条记录并获取每条记录的 id,它是自动递增的。我正在按照以下方式进行操作,但获取更新的行数而不是生成的密钥,在这种情况下为 id。

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;
}

这里 Person 是 bean。 那么,对于添加的记录,如何获取自动生成的密钥 id 呢?

【问题讨论】:

    标签: java mysql spring jdbc spring-jdbc


    【解决方案1】:

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

    【讨论】:

    • 现在我只使用executeAndReturnKey,但我认为这样做不是最佳做法,因为它会不必要地增加事务数量并保持服务器繁忙。
    • 是的,我同意你的观点,但我们对 API 有限制:(
    猜你喜欢
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多