1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.guice;
17
18 import static org.apache.ibatis.io.Resources.getResourceAsReader;
19 import static org.mybatis.guice.Preconditions.checkArgument;
20
21 import java.io.IOException;
22 import java.io.Reader;
23 import java.util.Collection;
24 import java.util.Properties;
25
26 import org.apache.ibatis.plugin.Interceptor;
27 import org.apache.ibatis.session.Configuration;
28 import org.apache.ibatis.session.SqlSessionFactory;
29 import org.apache.ibatis.session.SqlSessionFactoryBuilder;
30 import org.apache.ibatis.type.TypeHandler;
31
32
33
34
35
36 public abstract class XMLMyBatisModule extends AbstractMyBatisModule {
37
38 private static final String DEFAULT_CONFIG_RESOURCE = "mybatis-config.xml";
39
40 private static final String DEFAULT_ENVIRONMENT_ID = null;
41
42 private String classPathResource = DEFAULT_CONFIG_RESOURCE;
43
44 private String environmentId = DEFAULT_ENVIRONMENT_ID;
45
46 private Properties properties = new Properties();
47
48
49
50
51
52
53
54 protected final void setClassPathResource(String classPathResource) {
55 checkArgument(classPathResource != null, "Parameter 'classPathResource' must be not null");
56 this.classPathResource = classPathResource;
57 }
58
59
60
61
62
63
64
65 protected final void setEnvironmentId(String environmentId) {
66 this.environmentId = environmentId;
67 }
68
69
70
71
72
73
74
75 protected final void addProperties(Properties properties) {
76 if (properties != null) {
77 this.properties.putAll(properties);
78 }
79 }
80
81
82
83
84 @Override
85 final void internalConfigure() {
86 this.initialize();
87
88 Reader reader = null;
89 try {
90 reader = getResourceAsReader(getResourceClassLoader(), classPathResource);
91 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader, environmentId, properties);
92 bind(SqlSessionFactory.class).toInstance(sessionFactory);
93
94 Configuration configuration = sessionFactory.getConfiguration();
95
96
97 Collection<Class<?>> mapperClasses = configuration.getMapperRegistry().getMappers();
98 for (Class<?> mapperType : mapperClasses) {
99 bindMapper(mapperType);
100 }
101
102
103 Collection<TypeHandler<?>> allTypeHandlers = configuration.getTypeHandlerRegistry().getTypeHandlers();
104 for (TypeHandler<?> handler : allTypeHandlers) {
105 requestInjection(handler);
106 }
107
108
109 Collection<Interceptor> interceptors = configuration.getInterceptors();
110 for (Interceptor interceptor : interceptors) {
111 requestInjection(interceptor);
112 }
113
114
115 requestInjection(configuration.getObjectFactory());
116
117
118 requestInjection(configuration.getObjectWrapperFactory());
119 } catch (Exception e) {
120 addError("Impossible to read classpath resource '%s', see nested exceptions: %s", classPathResource,
121 e.getMessage());
122 } finally {
123 if (reader != null) {
124 try {
125 reader.close();
126 } catch (IOException e) {
127
128 }
129 }
130 }
131 }
132
133 }