Mybatis Insert后返回主键ID实现方法及源码分析

开发 前端
mybatis这类ORM在往数据库insert对象后,会顺带将数据库中的自增主键值赋值给对象的id,这个功能给我们的开发带来了很多方便,那它是怎么实现的呢?

[[409050]]

本文转载自微信公众号「肌肉码农」,作者邹学。转载本文请联系肌肉码农公众号。

引子:

mybatis这类ORM在往数据库insert对象后,会顺带将数据库中的自增主键值赋值给对象的id,这个功能给我们的开发带来了很多方便,那它是怎么实现的呢?

源码分析:

利用mybatis实现这一功能非常简单,网络上有一大把资料,今天我们主要看它是怎么实现的?

通过断点insert可以跟踪到这个类:PreparedStatementHandler.java的update方法。

  1. public int update(Statement statement) throws SQLException { 
  2.   PreparedStatement ps = (PreparedStatement) statement; 
  3. //执行insert操作 
  4.   ps.execute(); 
  5. //获得执行行数 
  6.   int rows = ps.getUpdateCount(); 
  7.   Object parameterObject = boundSql.getParameterObject(); 
  8.     //获得id 
  9.   KeyGenerator keyGenerator = mappedStatement.getKeyGenerator(); 
  10.   keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject); 
  11.   return rows

进一步跟踪getKeyGenerator()获得id的方法, 会进入Jdbc3KeyGenerator类的processBatch方法,如下:

  1. public void processBatch(MappedStatement ms, Statement stmt, Object parameter) { 
  2.     final String[] keyProperties = ms.getKeyProperties(); 
  3.     if (keyProperties == null || keyProperties.length == 0) { 
  4.       return
  5.     } 
  6.         //利用了statement的 getGeneratedKeys()方法 
  7.     try (ResultSet rs = stmt.getGeneratedKeys()) { 
  8.       final ResultSetMetaData rsmd = rs.getMetaData(); 
  9.       final Configuration configuration = ms.getConfiguration(); 
  10.       if (rsmd.getColumnCount() < keyProperties.length) { 
  11.         // Error? 
  12.       } else { 
  13.         assignKeys(configuration, rs, rsmd, keyProperties, parameter); 
  14.       } 
  15.     } catch (Exception e) { 
  16.       throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e); 
  17.     } 
  18.   } 

通过代码的注释我们可以看到,mybatis就是利用了Jdbc的Statement来获得会话insert id的,那我们可不可以自己直接利用jdbc来实现呢?

jdbc statement示例

首先创建一个test表:

  1. create table test id int  not null auto_increment, td intprimary key(id); 

然后执行以下代码就可以批量获得id了。

  1. Class.forName("com.mysql.jdbc.Driver"); 
  2.         Connection connection = DriverManager.getConnection(url, userName, pwd); 
  3.         String sql = "insert into test(td) values(5)"
  4.         Statement statement = connection.createStatement(); 
  5.         statement.execute(sql, 1); 
  6.  
  7.         ResultSet resultSet = statement.getGeneratedKeys(); 
  8.         while (resultSet.next()){ 
  9.             System.out.println(resultSet.getObject(1)); 
  10.         } 
  11.  
  12.         connection.close(); 

原理:

既然jdbc能获得insert后的id,那它是怎么实现的呢? 通过断点继续跟踪到这个类:StatementImpl.java

  1. protected ResultSetInternalMethods getGeneratedKeysInternal(long numKeys) throws SQLException { 
  2.         synchronized (checkClosed().getConnectionMutex()) { 
  3.             Field[] fields = new Field[1]; 
  4.             fields[0] = new Field("""GENERATED_KEY", Types.BIGINT, 20); 
  5.             fields[0].setConnection(this.connection); 
  6.             fields[0].setUseOldNameMetadata(true); 
  7.  
  8.             ArrayList<ResultSetRow> rowSet = new ArrayList<ResultSetRow>(); 
  9.  
  10.             //获得上一次获得insert后的id 
  11.             long beginAt = getLastInsertID(); 
  12.  
  13.             if (beginAt < 0) { // looking at an UNSIGNED BIGINT that has overflowed 
  14.                 fields[0].setUnsigned(); 
  15.             } 
  16.  
  17.             if (this.results != null) { 
  18.                 String serverInfo = this.results.getServerInfo(); 
  19.  
  20.                 // 
  21.                 // Only parse server info messages for 'REPLACE' queries 
  22.                 // 
  23.                 if ((numKeys > 0) && (this.results.getFirstCharOfQuery() == 'R') && (serverInfo != null) && (serverInfo.length() > 0)) { 
  24.                     //计算有多少行数据 
  25.                     numKeys = getRecordCountFromInfo(serverInfo); 
  26.                 } 
  27.                 //生成批量id 
  28.                 if ((beginAt != 0 /* BIGINT UNSIGNED can wrap the protocol representation */) && (numKeys > 0)) { 
  29.                     for (int i = 0; i < numKeys; i++) { 
  30.                         byte[][] row = new byte[1][]; 
  31.                         if (beginAt > 0) { 
  32.                             row[0] = StringUtils.getBytes(Long.toString(beginAt)); 
  33.                         } else { 
  34.                             byte[] asBytes = new byte[8]; 
  35.                             asBytes[7] = (byte) (beginAt & 0xff); 
  36.                             asBytes[6] = (byte) (beginAt >>> 8); 
  37.                             asBytes[5] = (byte) (beginAt >>> 16); 
  38.                             asBytes[4] = (byte) (beginAt >>> 24); 
  39.                             asBytes[3] = (byte) (beginAt >>> 32); 
  40.                             asBytes[2] = (byte) (beginAt >>> 40); 
  41.                             asBytes[1] = (byte) (beginAt >>> 48); 
  42.                             asBytes[0] = (byte) (beginAt >>> 56); 
  43.  
  44.                             BigInteger val = new BigInteger(1, asBytes); 
  45.  
  46.                             row[0] = val.toString().getBytes(); 
  47.                         } 
  48.                         rowSet.add(new ByteArrayRow(row, getExceptionInterceptor())); 
  49.                         beginAt += this.connection.getAutoIncrementIncrement(); 
  50.                     } 
  51.                 } 
  52.             } 
  53.  
  54.             com.mysql.jdbc.ResultSetImpl gkRs = com.mysql.jdbc.ResultSetImpl.getInstance(this.currentCatalog, fields, new RowDataStatic(rowSet), 
  55.                     this.connection, this, false); 
  56.  
  57.             return gkRs; 
  58.         } 
  59.     } 

代码的流程是这样的:获得上一次insert后的id,再计算本次插入数据的行数,最后自己批量生成,也就是说jdbc并没有一行一行的去数据库查询id.然后我们再看下它是怎么获得上一次insert后的Id的?

  1. /** 
  2. 支持自增主键 
  3.   * getLastInsertID returns the value of the auto_incremented key after an 
  4.   * executeQuery() or excute() call. 
  5.   *  
  6.   * <p> 
  7.   * 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 
  8.   * have had many INSERTS performed before one gets a chance to call "select LAST_INSERT_ID()"
  9.   * </p> 
  10.   *  
  11.   * @return the last update ID. 
  12.   */ 
  13.  public long getLastInsertID() { 
  14.      try { 
  15.          synchronized (checkClosed().getConnectionMutex()) { 
  16.              return this.lastInsertId; 
  17.          } 
  18.      } catch (SQLException e) { 
  19.          throw new RuntimeException(e); // evolve interface to throw SQLException 
  20.      } 
  21.  } 

光看上面的代码注释就明白了它的逻辑,通过select LAST_INSERT_ID()来获得会话内的insert后Id,并且只支持自增主键。

mysql client获得id

 

责任编辑:武晓燕 来源: 肌肉码农
相关推荐

2021-08-09 11:15:28

MybatisJavaSpring

2010-09-25 09:55:14

sql server主

2022-06-27 07:56:36

Mybatis源码Spring

2021-04-28 06:26:11

Spring Secu功能实现源码分析

2009-07-21 16:08:35

JDBC insert

2014-12-11 13:37:13

WPF架构

2023-11-09 09:08:38

RibbonSpring

2019-11-25 16:05:20

MybatisPageHelpeJava

2010-10-20 10:19:33

sql server删

2012-02-23 12:53:40

JavaPlay Framew

2010-10-19 17:34:10

sql server主

2020-05-28 16:50:59

源码分析 MybatisJava

2010-10-09 16:11:21

Mysql函数

2010-09-17 14:01:20

SQL插入

2013-08-28 10:11:37

RedisRedis主键失效NoSQL

2014-06-13 11:08:52

Redis主键失效

2014-06-17 10:27:39

Redis缓存

2020-10-09 14:13:04

Zookeeper Z

2024-01-22 08:46:37

MyBatis数据脱敏Spring

2015-11-23 09:50:15

JavaScript模块化SeaJs
点赞
收藏

51CTO技术栈公众号