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.annotation.KeyType; 019import com.mybatisflex.core.FlexConsts; 020import com.mybatisflex.core.exception.FlexExceptions; 021import com.mybatisflex.core.row.Row; 022import com.mybatisflex.core.row.RowKey; 023import com.mybatisflex.core.util.StringUtil; 024import org.apache.ibatis.executor.Executor; 025import org.apache.ibatis.executor.keygen.KeyGenerator; 026import org.apache.ibatis.mapping.MappedStatement; 027 028import java.sql.Statement; 029import java.util.Map; 030 031/** 032 * 通过 java 编码的方式生成主键 033 * 当主键类型配置为 KeyType#Generator 时,使用此生成器生成 034 * {@link KeyType#Generator} 035 */ 036public class RowCustomKeyGenerator implements KeyGenerator { 037 038 protected RowKey rowKey; 039 protected IKeyGenerator keyGenerator; 040 041 042 public RowCustomKeyGenerator(RowKey rowKey) { 043 this.rowKey = rowKey; 044 this.keyGenerator = KeyGeneratorFactory.getKeyGenerator(rowKey.getValue()); 045 046 ensuresKeyGeneratorNotNull(); 047 } 048 049 private void ensuresKeyGeneratorNotNull() { 050 if (keyGenerator == null) { 051 throw FlexExceptions.wrap("The name of \"%s\" key generator not exist.", rowKey.getValue()); 052 } 053 } 054 055 056 @Override 057 public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 058 Row row = (Row) ((Map) parameter).get(FlexConsts.ROW); 059 try { 060 Object existId = row.get(rowKey.getKeyColumn()); 061 // 若用户主动设置了主键,则使用用户自己设置的主键,不再生成主键 062 // 只有主键为 null 或者 空字符串时,对主键进行设置 063 if (existId == null || (existId instanceof String && StringUtil.noText((String) existId))) { 064 Object generateId = keyGenerator.generate(row, rowKey.getKeyColumn()); 065 row.put(rowKey.getKeyColumn(), generateId); 066 } 067 } catch (Exception e) { 068 throw FlexExceptions.wrap(e); 069 } 070 } 071 072 073 @Override 074 public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 075 //do nothing 076 } 077 078}