java - MyBatis如何获取Mysql自增id
本文介绍了java - 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语句呢。
解决方案
@Override
protected Statement instantiateStatement(Connection connection) throws SQLException {
String sql = boundSql.getSql();
if (mappedStatement.getKeyGenerator() instanceof Jdbc3KeyGenerator) {
String[] keyColumnNames = mappedStatement.getKeyColumns();
if (keyColumnNames == null) {
return connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
} else {
return connection.prepareStatement(sql, keyColumnNames);
}
} else if (mappedStatement.getResultSetType() != null) {
return connection.prepareStatement(sql, mappedStatement.getResultSetType().getValue(), ResultSet.CONCUR_READ_ONLY);
} else {
return connection.prepareStatement(sql);
}
}
这一段是Mybatis
中PreparedStatementHandler
的源码。大概意思是如果使用自动生成主键,并且值keyProperty
不为空,Statement
最后执行的时候会把keyProperty
涉及到的列值返回
这篇关于java - MyBatis如何获取Mysql自增id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文