Reputation: 1205
The code given below always returns zero for the last insert 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() });
Upvotes: 2
Views: 2348
Reputation: 340693
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.
Either use @Transactional
or wrap your JDBC call inside TransactionTemplate
.
Upvotes: 4