简体   繁体   中英

MySQL last_insert_id( ) returns 0 within the proper transaction

I have a Spring bean that:

  • inserts rows into a MySQL 5.6.12 table using JdbcTemplate
  • retrieves the IDs of the inserted rows using the MySQL last_insert_id( ) function

The ID column is defined as INT(10) UN AI PK :

@Repository @Transactional
public class UserDao
{
    @Autowired JdbcTemplate jdbcTemplate;

    public User create( User u ) {

        String   sql  = "insert ...";
        Object[] args = new Object[] { ... };

        int mod = jdbcTemplate.update( sql, args );
        int key = jdbcTemplate.queryForObject( "select last_insert_id( )", Integer.class );

        ...

    }
}

The DB is an Amazon RDS instance. When I execute the given code from my Windows development box, everything is fine. When I deploy the same app, with the same connection string, pool configuration etc. on an Ubuntu EC2 instance, last_insert_id( ) returns 0, always .

I've spent hours checking everything and I can state that the transaction is working properly, the insertion is fine etc. etc. Before tossing everything out of the window I replaced the .update/.query sequence with an .update( PreparedStatementCreator, KeyHolder ) and... keyHolder.getKey( ).intValue( ) works fine in both the environments...

I can't really understand what is the problem, if someone could shed some light...

The software stack, just in case: spring-jdbc-3.2.3.RELEASE, bonecp-0.7.1.RELEASE, mysql-connector-java-5.1.25. Java 7 on both machines.

也许尝试使用:mysql_insert_id()

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