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

com.penglecode.mybatis.ex.ExMapperRegistry Maven / Gradle / Ivy

Go to download

mybatis的自定义扩展。 版本1.0.0 支持mybatis 3.2|3.3版本 版本1.0.1 支持mybatis 3.4版本

There is a newer version: 1.0.1
Show newest version
package com.penglecode.mybatis.ex;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.ibatis.binding.BindingException;
import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;

public class ExMapperRegistry {

	private final Configuration config;
	private final Map, ExMapperProxyFactory> knownMappers = new HashMap, ExMapperProxyFactory>();

	public ExMapperRegistry(Configuration config) {
		this.config = config;
	}

	@SuppressWarnings("unchecked")
	public  T getMapper(Class type, SqlSession sqlSession) {
		final ExMapperProxyFactory mapperProxyFactory = (ExMapperProxyFactory) knownMappers.get(type);
		if (mapperProxyFactory == null) {
			throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
		}
		try {
			return mapperProxyFactory.newInstance(sqlSession);
		} catch (Exception e) {
			throw new BindingException("Error getting mapper instance. Cause: " + e, e);
		}
	}

	public  boolean hasMapper(Class type) {
		return knownMappers.containsKey(type);
	}

	public  void addMapper(Class type) {
		if (type.isInterface()) {
			if (hasMapper(type)) {
				throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
			}
			boolean loadCompleted = false;
			try {
				knownMappers.put(type, new ExMapperProxyFactory(type));
				// It's important that the type is added before the parser is
				// run
				// otherwise the binding may automatically be attempted by the
				// mapper parser. If the type is already known, it won't try.
				MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
				parser.parse();
				loadCompleted = true;
			} finally {
				if (!loadCompleted) {
					knownMappers.remove(type);
				}
			}
		}
	}

	/**
	 * @since 3.2.2
	 */
	public Collection> getMappers() {
		return Collections.unmodifiableCollection(knownMappers.keySet());
	}

	/**
	 * @since 3.2.2
	 */
	public void addMappers(String packageName, Class superType) {
		ResolverUtil> resolverUtil = new ResolverUtil>();
		resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
		Set>> mapperSet = resolverUtil.getClasses();
		for (Class mapperClass : mapperSet) {
			addMapper(mapperClass);
		}
	}

	/**
	 * @since 3.2.2
	 */
	public void addMappers(String packageName) {
		addMappers(packageName, Object.class);
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy