标签:database spring unique jdbctemplate persistent
当我使用Spring JDBCTemplate时,我得到了一个非常常见的问题,我想在将新数据记录插入数据库后获取ID值,此ID值将被引用到另一个相关表中.我尝试了以下方式插入它,但我总是返回1而不是它真正的唯一ID. (我使用MySQL作为数据库)
public int insert(BasicModel entity) {
String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
log.info("SQL Statement for inserting into: " + insertIntoSql);
return this.jdbcTemplate.update(insertIntoSql);
}
解决方法:
the number of rows affected
对于INSERT语句,始终为1.不同的数据库以不同的方式支持生成的密钥提取,但是大多数JDBC驱动程序都是抽象的,JdbcTemplate支持这一点.引用12.2.8 Retrieving auto-generated keys
An
update()
convenience method supports the retrieval of primary keys generated by the database. This support is part of the JDBC 3.0 standard; see Chapter 13.6 of the specification for details.
基本上你需要这个更冗长的陈述:
final String insertIntoSql = QueryUtil.getInsertIntoSqlStatement(entity);
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(
new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
return connection.prepareStatement(insertIntoSql, new String[] {"id"});
}
}, keyHolder);
return keyHolder.getKey().intValue();
标签:database,spring,unique,jdbctemplate,persistent 来源: https://codeday.me/bug/20190517/1123288.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。