MyBatis如何获取Mysql自增id

  <insert id="insert" useGeneratedKeys="true" keyProperty="id">

        INSERT INTO USER(name,age,address,loan_type)

        VALUES(#{name},#{age},#{address},#{loanType});

    </insert>

user表中id自增,添加过一条数据后,可以得到主键id;


DEBUG [main] - ==>  Preparing: INSERT INTO USER(name,age,address,loan_type) VALUES(?,?,?,?); 

DEBUG [main] - ==> Parameters: wrh(String), 26(Integer), 哈哈(String), 123(String)

DEBUG [main] - <==    Updates: 1

log信息。

那么问题来了,MyBatis是如何添加完一条数据后得到主键id呢?是insert之后再select嘛,但没有看到select语句呢。


慕尼黑8549860
浏览 1648回答 3
3回答

拉莫斯之舞

@Override&nbsp; protected Statement instantiateStatement(Connection connection) throws SQLException {&nbsp; &nbsp; String sql = boundSql.getSql();&nbsp; &nbsp; if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {&nbsp; &nbsp; &nbsp; String[] keyColumnNames = mappedStatement.getKeyColumns();&nbsp; &nbsp; &nbsp; if (keyColumnNames == null) {&nbsp; &nbsp; &nbsp; &nbsp; return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);&nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; return connection.prepareStatement(sql, keyColumnNames);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } else if (mappedStatement.getResultSetType() != null) {&nbsp; &nbsp; &nbsp; return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; return connection.prepareStatement(sql);&nbsp; &nbsp; }&nbsp; }这一段是Mybatis中PreparedStatementHandler的源码。大概意思是如果使用自动生成主键,并且值keyProperty不为空,Statement最后执行的时候会把keyProperty涉及到的列值返回

杨__羊羊

在insert标签中添加如下代码:<selectKey resultType="int" order="AFTER" keyProperty="id">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SELECT LAST_INSERT_ID()</selectKey>添加之后,会在对象添加之后自动填入id

蛊毒传说

<selectKey resultType="int" order="AFTER" keyProperty="id">SELECT&nbsp;...</selectKey>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java