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.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 org.apache.ibatis.executor.Executor; 024import org.apache.ibatis.executor.keygen.KeyGenerator; 025import org.apache.ibatis.mapping.MappedStatement; 026 027import java.sql.Statement; 028import java.util.Map; 029 030/** 031 * 通过 java 编码的方式生成主键 032 * 当主键类型配置为 KeyType#Generator 时,使用此生成器生成 033 * {@link KeyType#Generator} 034 */ 035public class RowCustomKeyGenerator implements KeyGenerator { 036 037 protected RowKey rowKey; 038 protected IKeyGenerator keyGenerator; 039 040 041 public RowCustomKeyGenerator(RowKey rowKey) { 042 this.rowKey = rowKey; 043 this.keyGenerator = KeyGeneratorFactory.getKeyGenerator(rowKey.getValue()); 044 045 ensuresKeyGeneratorNotNull(); 046 } 047 048 private void ensuresKeyGeneratorNotNull() { 049 if (keyGenerator == null) { 050 throw FlexExceptions.wrap("The name of \"%s\" key generator not exist.", rowKey.getValue()); 051 } 052 } 053 054 055 @Override 056 public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 057 Row row = (Row) ((Map) parameter).get(FlexConsts.ROW); 058 Object generateId = keyGenerator.generate(row, rowKey.getKeyColumn()); 059 try { 060 row.put(rowKey.getKeyColumn(), generateId); 061 } catch (Exception e) { 062 throw FlexExceptions.wrap(e); 063 } 064 } 065 066 067 @Override 068 public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) { 069 //do nothing 070 } 071}