Mybatis Insert后返回主鍵ID實(shí)現(xiàn)方法及源碼分析
本文轉(zhuǎn)載自微信公眾號(hào)「肌肉碼農(nóng)」,作者鄒學(xué)。轉(zhuǎn)載本文請(qǐng)聯(lián)系肌肉碼農(nóng)公眾號(hào)。
引子:
mybatis這類ORM在往數(shù)據(jù)庫insert對(duì)象后,會(huì)順帶將數(shù)據(jù)庫中的自增主鍵值賦值給對(duì)象的id,這個(gè)功能給我們的開發(fā)帶來了很多方便,那它是怎么實(shí)現(xiàn)的呢?
源碼分析:
利用mybatis實(shí)現(xiàn)這一功能非常簡(jiǎn)單,網(wǎng)絡(luò)上有一大把資料,今天我們主要看它是怎么實(shí)現(xiàn)的?
通過斷點(diǎn)insert可以跟蹤到這個(gè)類:PreparedStatementHandler.java的update方法。
- public int update(Statement statement) throws SQLException {
- PreparedStatement ps = (PreparedStatement) statement;
- //執(zhí)行insert操作
- ps.execute();
- //獲得執(zhí)行行數(shù)
- int rows = ps.getUpdateCount();
- Object parameterObject = boundSql.getParameterObject();
- //獲得id
- KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
- keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);
- return rows;
- }
進(jìn)一步跟蹤getKeyGenerator()獲得id的方法, 會(huì)進(jìn)入Jdbc3KeyGenerator類的processBatch方法,如下:
- public void processBatch(MappedStatement ms, Statement stmt, Object parameter) {
- final String[] keyProperties = ms.getKeyProperties();
- if (keyProperties == null || keyProperties.length == 0) {
- return;
- }
- //利用了statement的 getGeneratedKeys()方法
- try (ResultSet rs = stmt.getGeneratedKeys()) {
- final ResultSetMetaData rsmd = rs.getMetaData();
- final Configuration configuration = ms.getConfiguration();
- if (rsmd.getColumnCount() < keyProperties.length) {
- // Error?
- } else {
- assignKeys(configuration, rs, rsmd, keyProperties, parameter);
- }
- } catch (Exception e) {
- throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e);
- }
- }
通過代碼的注釋我們可以看到,mybatis就是利用了Jdbc的Statement來獲得會(huì)話insert id的,那我們可不可以自己直接利用jdbc來實(shí)現(xiàn)呢?
jdbc statement示例
首先創(chuàng)建一個(gè)test表:
- create table test id int not null auto_increment, td int, primary key(id);
然后執(zhí)行以下代碼就可以批量獲得id了。
- Class.forName("com.mysql.jdbc.Driver");
- Connection connection = DriverManager.getConnection(url, userName, pwd);
- String sql = "insert into test(td) values(5)";
- Statement statement = connection.createStatement();
- statement.execute(sql, 1);
- ResultSet resultSet = statement.getGeneratedKeys();
- while (resultSet.next()){
- System.out.println(resultSet.getObject(1));
- }
- connection.close();
原理:
既然jdbc能獲得insert后的id,那它是怎么實(shí)現(xiàn)的呢? 通過斷點(diǎn)繼續(xù)跟蹤到這個(gè)類:StatementImpl.java
- protected ResultSetInternalMethods getGeneratedKeysInternal(long numKeys) throws SQLException {
- synchronized (checkClosed().getConnectionMutex()) {
- Field[] fields = new Field[1];
- fields[0] = new Field("", "GENERATED_KEY", Types.BIGINT, 20);
- fields[0].setConnection(this.connection);
- fields[0].setUseOldNameMetadata(true);
- ArrayList<ResultSetRow> rowSet = new ArrayList<ResultSetRow>();
- //獲得上一次獲得insert后的id
- long beginAt = getLastInsertID();
- if (beginAt < 0) { // looking at an UNSIGNED BIGINT that has overflowed
- fields[0].setUnsigned();
- }
- if (this.results != null) {
- String serverInfo = this.results.getServerInfo();
- //
- // Only parse server info messages for 'REPLACE' queries
- //
- if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R') && (serverInfo != null) && (serverInfo.length() > 0)) {
- //計(jì)算有多少行數(shù)據(jù)
- numKeys = getRecordCountFromInfo(serverInfo);
- }
- //生成批量id
- if ((beginAt != 0 /* BIGINT UNSIGNED can wrap the protocol representation */) && (numKeys > 0)) {
- for (int i = 0; i < numKeys; i++) {
- byte[][] row = new byte[1][];
- if (beginAt > 0) {
- row[0] = StringUtils.getBytes(Long.toString(beginAt));
- } else {
- byte[] asBytes = new byte[8];
- asBytes[7] = (byte) (beginAt & 0xff);
- asBytes[6] = (byte) (beginAt >>> 8);
- asBytes[5] = (byte) (beginAt >>> 16);
- asBytes[4] = (byte) (beginAt >>> 24);
- asBytes[3] = (byte) (beginAt >>> 32);
- asBytes[2] = (byte) (beginAt >>> 40);
- asBytes[1] = (byte) (beginAt >>> 48);
- asBytes[0] = (byte) (beginAt >>> 56);
- BigInteger val = new BigInteger(1, asBytes);
- row[0] = val.toString().getBytes();
- }
- rowSet.add(new ByteArrayRow(row, getExceptionInterceptor()));
- beginAt += this.connection.getAutoIncrementIncrement();
- }
- }
- }
- com.mysql.jdbc.ResultSetImpl gkRs = com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields, new RowDataStatic(rowSet),
- this.connection, this, false);
- return gkRs;
- }
- }
代碼的流程是這樣的:獲得上一次insert后的id,再計(jì)算本次插入數(shù)據(jù)的行數(shù),最后自己批量生成,也就是說jdbc并沒有一行一行的去數(shù)據(jù)庫查詢id.然后我們?cè)倏聪滤窃趺传@得上一次insert后的Id的?
- /**
- 支持自增主鍵
- * getLastInsertID returns the value of the auto_incremented key after an
- * executeQuery() or excute() call.
- *
- * <p>
- * This gets around the un-threadsafe behavior of "select LAST_INSERT_ID()" which is tied to the Connection that created this Statement, and therefore could
- * have had many INSERTS performed before one gets a chance to call "select LAST_INSERT_ID()".
- * </p>
- *
- * @return the last update ID.
- */
- public long getLastInsertID() {
- try {
- synchronized (checkClosed().getConnectionMutex()) {
- return this.lastInsertId;
- }
- } catch (SQLException e) {
- throw new RuntimeException(e); // evolve interface to throw SQLException
- }
- }
光看上面的代碼注釋就明白了它的邏輯,通過select LAST_INSERT_ID()來獲得會(huì)話內(nèi)的insert后Id,并且只支持自增主鍵。
mysql client獲得id