001/* 002 * Copyright (c) 2022-2023, Mybatis-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.mybatisflex.core.keygen; 017 018import com.mybatisflex.core.FlexConsts; 019import com.mybatisflex.core.row.Row; 020import com.mybatisflex.core.util.CollectionUtil; 021import org.apache.ibatis.executor.Executor; 022import org.apache.ibatis.executor.keygen.KeyGenerator; 023import org.apache.ibatis.mapping.MappedStatement; 024 025import java.sql.Statement; 026import java.util.List; 027import java.util.Map; 028 029/** 030 * 用于批量插入的场景 031 */ 032public class MultiRowKeyGenerator implements KeyGenerator { 033 034 private final KeyGenerator keyGenerator; 035 036 public MultiRowKeyGenerator(KeyGenerator keyGenerator) { 037 this.keyGenerator = keyGenerator; 038 } 039 040 @Override 041 public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 042 List<Row> rows = (List<Row>) ((Map) parameter).get(FlexConsts.ROWS); 043 if (CollectionUtil.isNotEmpty(rows)) { 044 for (Row entity : rows) { 045 ((Map) parameter).put(FlexConsts.ROW, entity); 046 keyGenerator.processBefore(executor, ms, stmt, parameter); 047 } 048 } 049 } 050 051 052 @Override 053 public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 054 // do nothing 055 // 多条数据批量插入的场景下,不支持后设置主键 056 // 比如 INSERT INTO `tb_account`(uuid,name,sex) VALUES (?, ?, ?), (?, ?, ?) 057 } 058 059}