我github博客地址html
Mybatis中配置了Insert 操做時,添加了 useGeneratedKeys = true 的配置,就能夠在插入的model完成後獲取到主鍵的值,用於業務
1.有些場景,插入表單完須要返回id做,後續操做
複製代碼
/**
* @param
* @Author: zhuangjiesen
* @Description:
* @Date: Created in 2018/6/19
*/
@Mapper
public interface UserMapper {
@Insert("INSERT INTO `dragsunweb`.`user`(`user_id`, `user_name`, `user_password`) VALUES (#{id}, #{name}, #{password})")
@Options(useGeneratedKeys = true)
public Integer insert(User user);
}
複製代碼
Mybatis都是講mappper類掃描後,經過組裝(BeanDefinition)成 MapperFactoryBean.class,
而後最後經過MapperProxy.class(代理) 將mapper實例化,
給人的體驗就是能夠直接調用mapper操做數據庫
一個insert執行順序(一步步打斷點):
1.UserMapper.insert();
2.MapperProxy.invoke();
3.mapperMethod.execute();
4.DefaultSqlSession.insert();
5.BaseExecutor.update()
6.SimpleExecutor.doUpdate();
7.StatementHandler.update();
8.PreparedStatementHandler.update();
在8中就能夠發現執行完sql 後,調用的KeyGenerator
複製代碼
public class PreparedStatementHandler extends BaseStatementHandler {
@Override
public int update(Statement statement) throws SQLException {
PreparedStatement ps = (PreparedStatement) statement;
ps.execute();
int rows = ps.getUpdateCount();
Object parameterObject = boundSql.getParameterObject();
//調用 KeyGenerator
KeyGenerator keyGenerator = mappedStatement.getKeyGenerator();
keyGenerator.processAfter(executor, mappedStatement, ps, parameterObject);
return rows;
}
}
複製代碼
/**
* @author Clinton Begin
*/
public interface KeyGenerator {
void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter);
void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter);
}
複製代碼
這裏有個問題其實 KeyGenerator.class 能夠用來做攔截器的工做,或者拓展,
但是在 MappedStatement.class的內部構造類 Builder.class 中,只能默認使用2個類
複製代碼
NoKeyGenerator.class (若是不配置useKeyGenerator)
Jdbc3KeyGenerator.class (本次博客的主角)
複製代碼
/**
* @author Clinton Begin
* @author Kazuki Shimizu
*/
public class Jdbc3KeyGenerator implements KeyGenerator {
/**
* A shared instance.
* @since 3.4.3
*/
public static final Jdbc3KeyGenerator INSTANCE = new Jdbc3KeyGenerator();
@Override
public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
// do nothing
}
@Override
public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
processBatch(ms, stmt, getParameters(parameter));
}
public void processBatch(MappedStatement ms, Statement stmt, Collection<Object> parameters) {
ResultSet rs = null;
try {
//這裏獲取到執行的sql結果 , 獲取主鍵的字段值(實體類的映射),而後set進去很簡單
rs = stmt.getGeneratedKeys();
final Configuration configuration = ms.getConfiguration();
final TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
final String[] keyProperties = ms.getKeyProperties();
final ResultSetMetaData rsmd = rs.getMetaData();
TypeHandler<?>[] typeHandlers = null;
if (keyProperties != null && rsmd.getColumnCount() >= keyProperties.length) {
for (Object parameter : parameters) {
// there should be one row for each statement (also one for each parameter)
if (!rs.next()) {
break;
}
final MetaObject metaParam = configuration.newMetaObject(parameter);
if (typeHandlers == null) {
typeHandlers = getTypeHandlers(typeHandlerRegistry, metaParam, keyProperties, rsmd);
}
//獲取插入的對象參數,把主鍵值插入回對象屬性
populateKeys(rs, metaParam, keyProperties, typeHandlers);
}
}
} catch (Exception e) {
throw new ExecutorException("Error getting generated key or setting result to parameter object. Cause: " + e, e);
} finally {
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
// ignore
}
}
}
}
private Collection<Object> getParameters(Object parameter) {
Collection<Object> parameters = null;
if (parameter instanceof Collection) {
parameters = (Collection) parameter;
} else if (parameter instanceof Map) {
Map parameterMap = (Map) parameter;
if (parameterMap.containsKey("collection")) {
parameters = (Collection) parameterMap.get("collection");
} else if (parameterMap.containsKey("list")) {
parameters = (List) parameterMap.get("list");
} else if (parameterMap.containsKey("array")) {
parameters = Arrays.asList((Object[]) parameterMap.get("array"));
}
}
if (parameters == null) {
parameters = new ArrayList<Object>();
parameters.add(parameter);
}
return parameters;
}
private TypeHandler<?>[] getTypeHandlers(TypeHandlerRegistry typeHandlerRegistry, MetaObject metaParam, String[] keyProperties, ResultSetMetaData rsmd) throws SQLException {
TypeHandler<?>[] typeHandlers = new TypeHandler<?>[keyProperties.length];
for (int i = 0; i < keyProperties.length; i++) {
if (metaParam.hasSetter(keyProperties[i])) {
TypeHandler<?> th;
try {
Class<?> keyPropertyType = metaParam.getSetterType(keyProperties[i]);
th = typeHandlerRegistry.getTypeHandler(keyPropertyType, JdbcType.forCode(rsmd.getColumnType(i + 1)));
} catch (BindingException e) {
th = null;
}
typeHandlers[i] = th;
}
}
return typeHandlers;
}
private void populateKeys(ResultSet rs, MetaObject metaParam, String[] keyProperties, TypeHandler<?>[] typeHandlers) throws SQLException {
for (int i = 0; i < keyProperties.length; i++) {
String property = keyProperties[i];
TypeHandler<?> th = typeHandlers[i];
if (th != null) {
Object value = th.getResult(rs, i + 1);
metaParam.setValue(property, value);
}
}
}
}
複製代碼
這裏就會發現其實insert操做完獲取主鍵直接能夠經過 ResultSet 獲取到。而 KeyGenerator.class其實就是個設計模式封裝而已。
經過斷點發現JDBC 的 ResultSetImpl.class (ResultSet.class 接口實現) ,實際上是有字段 resultId 、 updateId (mysql註釋: /** Value generated for AUTO_INCREMENT columns */ -> 就是自增主鍵的值 )
還有個字段是 updateCount (mysql註釋: /** How many rows were affected by UPDATE/INSERT/DELETE? */ -> 就是影響行數 )
複製代碼
public static void main(String[] args ) throws Exception {
Connection conn = getConn();
int i = 0;
String sql = " INSERT INTO `dragsunweb`.`user` ( `user_id`, `user_name`, `user_password` ) VALUES ( null , 'hahaha', '2233' )";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement) conn.prepareStatement(sql);
long id = 0L;
//這裏能夠獲取執行行數
i = pstmt.executeUpdate();
//這裏能夠查看到最後插入的主鍵值
id = pstmt.getLastInsertID();
System.out.println(String.format("1. id : %d , rows : %d " , id , i));
i = pstmt.executeUpdate();
id = pstmt.getLastInsertID();
System.out.println(String.format("2. id : %d , rows : %d " , id , i));
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
------
結果就是如我所說,打印出了對應的主鍵值
複製代碼
1.是1條sql(insert)就能夠獲取到主鍵的值嗎,平時在可視化工具中執行的時候只能獲取影響行數;
2.經過mysql配置或是多條語句
複製代碼
代碼就不貼了,很抽象
步驟是
1.序列化參數
2.序列化sql
3.格式化mysql 通訊協議
4.獲取mysql 鏈接
5.發送mysql請求
6.獲取返回報文
----如下是源碼執行順序-----
PreparedStatement.execute();
//搜這個關鍵代碼塊
Buffer sendPacket = fillSendPacket();
fillSendPacket();//用來封裝發送的mysql報文協議
executeInternal();方法中發送了請求
ConnectionImpl.execSQL()
//MysqlIO這裏有mysql的協議封裝
MysqlIO.sqlQueryDirect();//發送請求
MysqlIO.readAllResults()//解析返回值報文
複製代碼
mysql的協議中,服務器響應報文是對於insert/update/delete是有返回主鍵值的,只是應用層中沒有給出接口
4.3.1 OK 響應報文
客戶端的命令執行正確時,服務器會返回OK響應報文。
MySQL 4.0 及以前的版本
字節 說明
1 OK報文,值恆爲0x00
1-9 受影響行數(Length Coded Binary)
1-9 索引ID值(Length Coded Binary)
2 服務器狀態
n 服務器消息(字符串到達消息尾部時結束,無結束符)
複製代碼
MySQL協議分析mysql
mysql網絡協議官網git