Java Spring JdbcTemplate无法从MySQL获取插入ID
我正在尝试向MySQL表中插入一行并获取其插入ID。我知道MySQL的Java Spring JdbcTemplate无法从MySQL获取插入ID,java,mysql,sql,spring,Java,Mysql,Sql,Spring,我正在尝试向MySQL表中插入一行并获取其插入ID。我知道MySQL的last\u insert\u ID()函数,但似乎无法使其正常工作。目前,我正在尝试使用注释为事务的函数,只返回0。我正在使用Spring3.1 @Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class) private long insertTransactionRecord (
last\u insert\u ID()
函数,但似乎无法使其正常工作。目前,我正在尝试使用注释为事务的函数,只返回0。我正在使用Spring3.1
@Transactional (propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
private long insertTransactionRecord
(
int custID,
int porID,
String date,
short crvID
) {
m_template.update ("INSERT INTO " +
" transaction " +
"( " +
" por_id, " +
" cust_id, " +
" trans_date, " +
" crv_id " +
") " +
"VALUES " +
"( " +
" ?, " +
" ?, " +
" ?, " +
" ? " +
")",
new Object[] {
porID,
custID,
date,
crvID
});
return m_template.queryForLong ("SELECT " +
" last_insert_id() " +
"FROM " +
" transaction " +
"LIMIT 1");
}
从这里开始
如果您注意到没有来自的,则显示获取最后一个插入ID的语法是:
SELECT LAST_INSERT_ID()
使用Spring的内置支持,而不是自己做
SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"});
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());
FROM
子句的目的是指定要从中获取ID的表JdbcTemplate
使用连接池,因此不能保证我在同一个连接上。这笔交易本应弥补这一缺陷。不过,您的建议没有帮助,谢谢。使用jdbcTemplate.queryForObject(“select last_insert_id()”,Integer.class)我认为这种方法不会是线程安全的,是吗?queryForInt(..)调用可能在多次插入之后发生,并为其上方的insert语句返回错误的ID。@MarkRoper-据我所知,一旦正确配置JDBC,它就是线程安全的,根据我的经验,它是现成正确配置的。在这里读:我明白。它在JdbcTemplate
中不起作用。如果我在MySQL客户端中手动运行它,它会起作用。如果您了解这一点,为什么要使用SELECT last\u insert\u id()FROM transaction LIMIT 1
?因为JdbcTemplate
使用连接池,所以我不能保证从正确的表中获取id。包含FROM
子句在MySQL客户端中有效。有些博客文章建议采用这种做法。Spring不可能对同一数据库事务中执行的两条语句使用两个不同的JDBC连接。如果它这样做了,就不会再有什么交易性了。使用文档中告诉您要使用的内容。并阅读它以了解它的作用。此外,当我从
中取出时,它不会修复任何东西。Spring在手册中也有一个示例:
SqlUpdate insert = new SqlUpdate(ds, "INSERT INTO company (name) VALUES (?)");
insert.declareParameter(new SqlParameter(Types.VARCHAR));
insert.setReturnGeneratedKeys(true);
// assuming auto-generated col is named 'id'
insert.setGeneratedKeysColumnNames(new String[] {"id"});
insert.compile();
....
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
insert.update(new Object[]{"test"}, keyHolder);
System.out.println(keyHolder.getKey().longValue());