[英]spring jdbctemplate returns 0 for last_insert_id()
The code given below always returns zero for the last insert id. 下面给出的代码对于最后一个插入ID始终返回零。 Can you please explain me what is wrong with this code?
您能解释一下这段代码有什么问题吗?
JdbcTemplate insert = new JdbcTemplate(dataSource);
insert.update("INSERT INTO item (price, item_category) VALUES(?,?)",
new Object[] { beverage.getPrice(), beverage.getItemCategory() });
int id = insert.queryForInt( "SELECT last_insert_id()" );
System.out.println(id);
return insert.update("INSERT INTO beverage (id, name, quantity,size) VALUES(?,?,?,?)", new Object[] { id,beverage.getName(), beverage.getQuantity(),beverage.getSize() });
The whole code above must be wrapped in a transaction. 上面的整个代码必须包装在事务中。 Otherwise
JdbcTemplate
can use a different connection from the pool for all statements and last_insert_id()
is tied to a transaction. 否则,
JdbcTemplate
可以对所有语句使用与池不同的连接,并且last_insert_id()
与事务绑定。
Either use @Transactional
or wrap your JDBC call inside TransactionTemplate
. 使用
@Transactional
或将JDBC调用包装在TransactionTemplate
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.