在mybatis使用过程中,如果需要自定义mybatis使用的数据源的话,那么需要做如下操作:
1、添加需要的数据库连接池的jar包,或者添加相关的maven配置;
2、自定义DataSourceFactory类,继承UnpooledDataSourceFactory,通过带参构造方法实现DataSource的注入;
3、看需要修改mybatis-config.xml配置文件,修改属性配置。
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
public class DruidDataSourceFactory extends UnpooledDataSourceFactory {
public DruidDataSourceFactory(){
this.dataSource = new DruidDataSource();
}
}
<dataSource type="com.huwc.factory.DruidDataSourceFactory">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///test?&useUnicode=false&characterEncoding=utf8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
通过以上两个步骤,即修改了默认的数据库连接池配置,将mybatis中集成了druid的数据库连接池。
那么我们从源码级别来梳理一下,这个druid数据库连接池究竟是怎么集成进来的。
首先,DataSource是作为一个属性配置在Configuration类中的,Configuration对象会作为SqlSessionFactory的属性存在,那么SqlSessionFactory在openSession操作中,就能通过Configuration中的DataSource来获取Connection了。
整个Configuration对象的初始化,是通过XMLConfigBuilder中的parseConfiguration方法来处理的。
private void parseConfiguration(XNode root) {
try {
//issue #117 read properties first
propertiesElement(root.evalNode("properties"));
Properties settings = settingsAsProperties(root.evalNode("settings"));
loadCustomVfs(settings);
typeAliasesElement(root.evalNode("typeAliases"));
pluginElement(root.evalNode("plugins"));
objectFactoryElement(root.evalNode("objectFactory"));
objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
reflectorFactoryElement(root.evalNode("reflectorFactory"));
settingsElement(settings);
// read it after objectFactory and objectWrapperFactory issue #631
environmentsElement(root.evalNode("environments"));
databaseIdProviderElement(root.evalNode("databaseIdProvider"));
typeHandlerElement(root.evalNode("typeHandlers"));
mapperElement(root.evalNode("mappers"));
} catch (Exception e) {
throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
}
}
上面方法中的environmentsElement就是初始化environments配置的,我们知道,DataSource就是配置在environment中的,
private void environmentsElement(XNode context) throws Exception {
if (context != null) {
if (environment == null) {
environment = context.getStringAttribute("default");
}
for (XNode child : context.getChildren()) {
String id = child.getStringAttribute("id");
if (isSpecifiedEnvironment(id)) {
TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
DataSource dataSource = dsFactory.getDataSource();
Environment.Builder environmentBuilder = new Environment.Builder(id)
.transactionFactory(txFactory)
.dataSource(dataSource);
configuration.setEnvironment(environmentBuilder.build());
}
}
}
}
上面的代码可以看出,先是根据mybatis-config.xml中的配置初始化了DataSourceFactory,再通过getDataSource方法获取到了DataSource,相应的DataSourceFactory的初始化代码如下:
private DataSourceFactory dataSourceElement(XNode context) throws Exception {
if (context != null) {
String type = context.getStringAttribute("type");
Properties props = context.getChildrenAsProperties();
DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
factory.setProperties(props);
return factory;
}
throw new BuilderException("Environment declaration requires a DataSourceFactory.");
}
从上面的代码可以看出:
第一步:根据DataSource配置中的type属性,通过反射机制,实例化了DataSourceFactory对象;
第二步:对DataSourceFactory进行属性值的注入,实现初始化;
第三步:通过getDataSource方法获取对应的数据库连接池。
属性注入的代码如下:
public void setProperties(Properties properties) {
Properties driverProperties = new Properties();
MetaObject metaDataSource = SystemMetaObject.forObject(dataSource);
for (Object key : properties.keySet()) {
String propertyName = (String) key;
if (propertyName.startsWith(DRIVER_PROPERTY_PREFIX)) {
String value = properties.getProperty(propertyName);
driverProperties.setProperty(propertyName.substring(DRIVER_PROPERTY_PREFIX_LENGTH), value);
} else if (metaDataSource.hasSetter(propertyName)) {
String value = (String) properties.get(propertyName);
Object convertedValue = convertValue(metaDataSource, propertyName, value);
metaDataSource.setValue(propertyName, convertedValue);
} else {
throw new DataSourceException("Unknown DataSource property: " + propertyName);
}
}
if (driverProperties.size() > 0) {
metaDataSource.setValue("driverProperties", driverProperties);
}
}
可以看出, 此方法中对注入的数据库连接池进行了属性的设置,案例中,我们使用的是DruidDataSource,其中关于driver的属性名为driverClass,但是setter方法名称却为setDriverClassname,经过测试,配置文件中原本的driver修改为driverClass或者driverClassName都可以正确初始化数据库连接池。