首页 > Mybatis 在 insert 之后想获取自增的主键 id,但是总是返回1

Mybatis 在 insert 之后想获取自增的主键 id,但是总是返回1

<insert id="add"
        useGeneratedKeys="true" keyColumn="id" keyProperty="id"
        parameterType="user">
    INSERT INTO `user` (`name`,sex,register_ts) VALUES (#{name},#{sex},#{registerTs})
    <selectKey resultType="int" keyProperty="id" order="AFTER">
        SELECT LAST_INSERT_ID()
    </selectKey>
</insert>

数据能插入成功,但是总是返回1.
debug 数据插入的过程

19:01:24.389 [nioEventLoopGroup-3-1] DEBUG org.mybatis.spring.SqlSessionUtils - Creating a new SqlSession
19:01:24.389 [nioEventLoopGroup-3-1] DEBUG org.mybatis.spring.SqlSessionUtils - SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5521d0ca] was not registered for synchronization because synchronization is not active
19:01:24.390 [nioEventLoopGroup-3-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Fetching JDBC Connection from DataSource
19:01:24.390 [nioEventLoopGroup-3-1] DEBUG o.m.s.t.SpringManagedTransaction - JDBC Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@60e12da7 [wrapping: com.mysql.jdbc.JDBC4Connection@ae2b311]] will not be managed by Spring
19:01:24.390 [nioEventLoopGroup-3-1] DEBUG me.topit.awesome.t16.dao.UserDao.add - ooo Using Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@60e12da7 [wrapping: com.mysql.jdbc.JDBC4Connection@ae2b311]]
19:01:24.390 [nioEventLoopGroup-3-1] DEBUG me.topit.awesome.t16.dao.UserDao.add - ==>  Preparing: INSERT INTO `user` (`name`,sex,register_ts) VALUES (?,?,?) 
19:01:24.391 [nioEventLoopGroup-3-1] DEBUG me.topit.awesome.t16.dao.UserDao.add - ==> Parameters: mengkang7(String), 1(Integer), 1453460484(Integer)
19:01:24.394 [nioEventLoopGroup-3-1] DEBUG me.topit.awesome.t16.dao.UserDao.add - <==    Updates: 1
19:01:24.394 [nioEventLoopGroup-3-1] DEBUG m.t.a.t16.dao.UserDao.add!selectKey - ooo Using Connection [com.mchange.v2.c3p0.impl.NewProxyConnection@60e12da7 [wrapping: com.mysql.jdbc.JDBC4Connection@ae2b311]]
19:01:24.395 [nioEventLoopGroup-3-1] DEBUG m.t.a.t16.dao.UserDao.add!selectKey - ==>  Preparing: SELECT LAST_INSERT_ID() 
19:01:24.395 [nioEventLoopGroup-3-1] DEBUG m.t.a.t16.dao.UserDao.add!selectKey - ==> Parameters: 
19:01:24.397 [nioEventLoopGroup-3-1] DEBUG m.t.a.t16.dao.UserDao.add!selectKey - <==      Total: 1
19:01:24.397 [nioEventLoopGroup-3-1] DEBUG org.mybatis.spring.SqlSessionUtils - Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5521d0ca]
19:01:24.397 [nioEventLoopGroup-3-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource

1是返回的插入成功的行数;自增id直接映射到你的对象里了,直接输出 xxx.getId()就可以了

另外 在Mybatis中,selectKey那一句也不需要了

【热门文章】
【热门文章】