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

周梦康
  • 8.9k
<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 [[email protected]] 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 [[email protected] [wrapping: [email protected]]] will not be managed by Spring
19:01:24.390 [nioEventLoopGroup-3-1] DEBUG me.topit.awesome.t16.dao.UserDao.add - ooo Using Connection [[email protected] [wrapping: [email protected]]]
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 [[email protected] [wrapping: [email protected]]]
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 [[email protected]]
19:01:24.397 [nioEventLoopGroup-3-1] DEBUG o.s.jdbc.datasource.DataSourceUtils - Returning JDBC Connection to DataSource
回复
阅读 30.3k
1 个回答
牧曦之晨
  • 1.1k
✓ 已被采纳

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

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏