All Downloads are FREE. Search and download functionalities are using the official Maven repository.

sf.database.mapper.DefaultMapperBuilder Maven / Gradle / Ivy

The newest version!
package sf.database.mapper;

import sf.database.dao.DBClient;

import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 默认Java代理实现.
 * @author
 */
public class DefaultMapperBuilder implements MapperBuilder {

    /**
     * The cache.
     */
    protected Map, Object> cache = new ConcurrentHashMap<>();

    /**
     * The db client.
     */
    protected DBClient client;


    /**
     * The Constructor.
     * @param client the db client
     */
    public DefaultMapperBuilder(DBClient client) {
        super();
        this.client = client;

    }

    @Override
    @SuppressWarnings("unchecked")
    public  T getMapper(Class mapperInterface) {
        if (cache.containsKey(mapperInterface)) {
            return (T) cache.get(mapperInterface);
        } else {
            T instance = this.buildInstance(mapperInterface);
            cache.put(mapperInterface, instance);
            return instance;
        }
    }

    /**
     * Builds the instance.
     * @param              the generic type
     * @param mapperInterface the dao interface
     * @return the t
     */
    @SuppressWarnings("unchecked")
    public  T buildInstance(Class mapperInterface) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        //使用ContextLoader,适合大多数框架
        return (T) Proxy.newProxyInstance(loader == null ? this.getClass().getClassLoader() : loader, new Class[]{mapperInterface},
                new MapperJavaProxy(this, client, mapperInterface));
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy