1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.binding;
17
18 import org.apache.ibatis.builder.annotation.MapperAnnotationBuilder;
19 import org.apache.ibatis.io.ResolverUtil;
20 import org.apache.ibatis.session.Configuration;
21 import org.apache.ibatis.session.SqlSession;
22
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.HashMap;
26 import java.util.Map;
27 import java.util.Set;
28
29
30
31
32
33
34 public class MapperRegistry {
35
36 private final Configuration config;
37 private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
38
39 public MapperRegistry(Configuration config) {
40 this.config = config;
41 }
42
43 @SuppressWarnings("unchecked")
44 public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
45 final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
46 if (mapperProxyFactory == null) {
47 throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
48 }
49 try {
50 return mapperProxyFactory.newInstance(sqlSession);
51 } catch (Exception e) {
52 throw new BindingException("Error getting mapper instance. Cause: " + e, e);
53 }
54 }
55
56 public <T> boolean hasMapper(Class<T> type) {
57 return knownMappers.containsKey(type);
58 }
59
60 public <T> void addMapper(Class<T> type) {
61 if (type.isInterface()) {
62 if (hasMapper(type)) {
63 throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
64 }
65 boolean loadCompleted = false;
66 try {
67 knownMappers.put(type, new MapperProxyFactory<T>(type));
68
69
70
71 MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
72 parser.parse();
73 loadCompleted = true;
74 } finally {
75 if (!loadCompleted) {
76 knownMappers.remove(type);
77 }
78 }
79 }
80 }
81
82
83
84
85 public Collection<Class<?>> getMappers() {
86 return Collections.unmodifiableCollection(knownMappers.keySet());
87 }
88
89
90
91
92 public void addMappers(String packageName, Class<?> superType) {
93 ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<Class<?>>();
94 resolverUtil.find(new ResolverUtil.IsA(superType), packageName);
95 Set<Class<? extends Class<?>>> mapperSet = resolverUtil.getClasses();
96 for (Class<?> mapperClass : mapperSet) {
97 addMapper(mapperClass);
98 }
99 }
100
101
102
103
104 public void addMappers(String packageName) {
105 addMappers(packageName, Object.class);
106 }
107
108 }