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.mybatis;
017
018import com.mybatisflex.core.BaseMapper;
019import com.mybatisflex.core.FlexGlobalConfig;
020import com.mybatisflex.core.exception.FlexExceptions;
021import org.apache.ibatis.reflection.ExceptionUtil;
022import org.apache.ibatis.session.ExecutorType;
023import org.apache.ibatis.session.SqlSession;
024import org.apache.ibatis.session.SqlSessionFactory;
025import com.mybatisflex.core.util.MapUtil;
026
027import java.lang.reflect.InvocationHandler;
028import java.lang.reflect.Method;
029import java.lang.reflect.Proxy;
030import java.util.Map;
031import java.util.concurrent.ConcurrentHashMap;
032
033/**
034 * 获取 {@link BaseMapper} 对象。
035 *
036 * @author michael
037 * @author 王帅
038 */
039@SuppressWarnings("unchecked")
040public class Mappers {
041
042    private Mappers() {
043    }
044
045    private static final Map<Class<?>, Object> MAPPER_OBJECTS = new ConcurrentHashMap<>();
046
047    private static final Map<Class<?>, Class<?>> ENTITY_MAPPER_MAP = new ConcurrentHashMap<>();
048
049    /**
050     * 添加 实体类 与 {@link BaseMapper} 接口实现接口 对应,两者皆为非动态代理类。
051     *
052     * @param entityClass 实体类
053     * @param mapperClass {@link BaseMapper} 实现接口
054     */
055    static void addMapping(Class<?> entityClass, Class<?> mapperClass) {
056        ENTITY_MAPPER_MAP.put(entityClass, mapperClass);
057    }
058
059    /**
060     * 通过 实体类 获取对应 {@link BaseMapper} 对象。
061     *
062     * @param entityClass 实体类
063     * @param <E>         实体类类型
064     * @return {@link BaseMapper} 对象
065     */
066    public static <E> BaseMapper<E> ofEntityClass(Class<E> entityClass) {
067        Class<?> mapperClass = ENTITY_MAPPER_MAP.get(entityClass);
068        if (mapperClass == null) {
069            throw FlexExceptions.wrap("Can not find MapperClass by entity: " + entityClass.getName());
070        }
071        return (BaseMapper<E>) ofMapperClass(mapperClass);
072    }
073
074    /**
075     * 通过 {@link BaseMapper} 接口实现的 Class 引用直接获取 {@link BaseMapper} 代理对象。
076     *
077     * @param mapperClass {@link BaseMapper} 接口实现
078     * @return {@link BaseMapper} 对象
079     */
080    public static <M> M ofMapperClass(Class<M> mapperClass) {
081        Object mapperObject = MapUtil.computeIfAbsent(MAPPER_OBJECTS, mapperClass, clazz ->
082            Proxy.newProxyInstance(mapperClass.getClassLoader()
083                , new Class[]{mapperClass}
084                , new MapperHandler(mapperClass)));
085        return (M) mapperObject;
086    }
087
088    private static class MapperHandler implements InvocationHandler {
089
090        private final Class<?> mapperClass;
091        private final ExecutorType executorType;
092        private final SqlSessionFactory sqlSessionFactory;
093
094        public MapperHandler(Class<?> mapperClass) {
095            this.mapperClass = mapperClass;
096            this.executorType = FlexGlobalConfig.getDefaultConfig()
097                .getConfiguration()
098                .getDefaultExecutorType();
099            this.sqlSessionFactory = FlexGlobalConfig.getDefaultConfig()
100                .getSqlSessionFactory();
101        }
102
103        private SqlSession openSession() {
104            return sqlSessionFactory.openSession(executorType, true);
105        }
106
107        @Override
108        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
109            try (SqlSession sqlSession = openSession()) {
110                Object mapper = sqlSession.getMapper(mapperClass);
111                return method.invoke(mapper, args);
112            } catch (Throwable throwable) {
113                throw ExceptionUtil.unwrapThrowable(throwable);
114            }
115        }
116
117    }
118
119}