001/*
002 *  Copyright (c) 2022-2025, 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.util.CollectionUtil;
020import org.apache.ibatis.executor.Executor;
021import org.apache.ibatis.executor.keygen.KeyGenerator;
022import org.apache.ibatis.mapping.MappedStatement;
023
024import java.sql.Statement;
025import java.util.List;
026import java.util.Map;
027
028/**
029 * 多实体主键生成器,用于批量插入的场景
030 */
031public class MultiEntityKeyGenerator implements KeyGenerator {
032
033    private final KeyGenerator keyGenerator;
034
035    public MultiEntityKeyGenerator(KeyGenerator keyGenerator) {
036        this.keyGenerator = keyGenerator;
037    }
038
039    @Override
040    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
041        List<Object> entities = (List<Object>) ((Map) parameter).get(FlexConsts.ENTITIES);
042        if (CollectionUtil.isNotEmpty(entities)) {
043            for (Object entity : entities) {
044                ((Map) parameter).put(FlexConsts.ENTITY, entity);
045                keyGenerator.processBefore(executor, ms, stmt, parameter);
046            }
047        }
048    }
049
050
051    @Override
052    public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
053        // do nothing
054        // 多条数据批量插入的场景下,不支持后设置主键
055        // 比如 INSERT INTO `tb_account`(uuid,name,sex) VALUES (?, ?, ?), (?, ?, ?)
056    }
057
058}