自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Mybatis Insert后返回主鍵ID實(shí)現(xiàn)方法及源碼分析

開發(fā) 前端
mybatis這類ORM在往數(shù)據(jù)庫insert對(duì)象后,會(huì)順帶將數(shù)據(jù)庫中的自增主鍵值賦值給對(duì)象的id,這個(gè)功能給我們的開發(fā)帶來了很多方便,那它是怎么實(shí)現(xiàn)的呢?

[[409050]]

本文轉(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方法。

  1. public int update(Statement statement) throws SQLException { 
  2.   PreparedStatement ps = (PreparedStatement) statement; 
  3. //執(zhí)行insert操作 
  4.   ps.execute(); 
  5. //獲得執(zhí)行行數(shù) 
  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

進(jìn)一步跟蹤getKeyGenerator()獲得id的方法, 會(huì)進(jìn)入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來獲得會(huì)話insert id的,那我們可不可以自己直接利用jdbc來實(shí)現(xiàn)呢?

jdbc statement示例

首先創(chuàng)建一個(gè)test表:

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

然后執(zhí)行以下代碼就可以批量獲得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,那它是怎么實(shí)現(xiàn)的呢? 通過斷點(diǎn)繼續(xù)跟蹤到這個(gè)類: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.                     //計(jì)算有多少行數(shù)據(jù) 
  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,再計(jì)算本次插入數(shù)據(jù)的行數(shù),最后自己批量生成,也就是說jdbc并沒有一行一行的去數(shù)據(jù)庫查詢id.然后我們?cè)倏聪滤窃趺传@得上一次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()來獲得會(huì)話內(nèi)的insert后Id,并且只支持自增主鍵。

mysql client獲得id

 

責(zé)任編輯:武曉燕 來源: 肌肉碼農(nóng)
相關(guān)推薦

2021-08-09 11:15:28

MybatisJavaSpring

2010-09-25 09:55:14

sql server主

2022-06-27 07:56:36

Mybatis源碼Spring

2024-11-22 15:32:19

2021-04-28 06:26:11

Spring Secu功能實(shí)現(xiàn)源碼分析

2009-07-21 16:08:35

JDBC insert

2023-11-09 09:08:38

RibbonSpring

2014-12-11 13:37:13

WPF架構(gòu)

2019-11-25 16:05:20

MybatisPageHelpeJava

2010-10-20 10:19:33

sql server刪

2012-02-23 12:53:40

JavaPlay Framew

2024-12-04 09:36:37

2020-05-28 16:50:59

源碼分析 MybatisJava

2010-10-19 17:34:10

sql server主

2020-10-09 14:13:04

Zookeeper Z

2014-06-13 11:08:52

Redis主鍵失效

2014-06-17 10:27:39

Redis緩存

2013-08-28 10:11:37

RedisRedis主鍵失效NoSQL

2010-10-09 16:11:21

Mysql函數(shù)

2015-11-23 09:50:15

JavaScript模塊化SeaJs
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)