Pages

Sunday, September 2, 2012

spring transaction management


recently I wrote a spring 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() });

How ever the id was always 0. There reason has been,

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.
Threfore @Transactional can be used to avoid this error.

How ever this solution can be applied only to non MyISAM type of tables. Because MyISAM type does not support transactions.

No comments:

Post a Comment