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.Collection;
026import java.util.List;
027import java.util.Map;
028
029/**
030 * 多实体主键生成器,用于批量插入的场景
031 */
032public class MultiEntityKeyGenerator implements KeyGenerator {
033
034    private final KeyGenerator keyGenerator;
035
036    public MultiEntityKeyGenerator(KeyGenerator keyGenerator) {
037        this.keyGenerator = keyGenerator;
038    }
039
040    @Override
041    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
042        Collection<Object> entities = (Collection<Object>) ((Map) parameter).get(FlexConsts.ENTITIES);
043        if (CollectionUtil.isNotEmpty(entities)) {
044            for (Object entity : entities) {
045                ((Map) parameter).put(FlexConsts.ENTITY, 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}