简体   繁体   中英

spring jdbctemplate returns 0 for last_insert_id()

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() });

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM