MyBatis在非Spring环境下第三方DataSource设置

Spring环境下, MyBatis可以通过其本身的增强mybatis-spring提供的org.mybatis.spring.SqlSessionFactoryBean来注入第三方DataSource.

但是在非Spring的环境下, MyBatis的加载需要配置其自身的configuration xml文件,

代码段可能是下面这样的:

<environments default="development">
  <environment id="development">
    <transactionManager type="JDBC">
      <property name="..." value="..."/>
    </transactionManager>
    <dataSource type="POOLED">
      <property name="driver" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
    </dataSource>
  </environment>
</environments>

 其中type属性, 只有三个值可以选择, UNPOOLED, POOLED, 和JNDI

事实上DataSource标签的属性Type注入的不是DataSource对象, 而是DataSourceFactory对象, 所以通过对Type进行DataSource的注入是错误的.

我们首先需要建一个自己的DataSourceFactory类, 用来封装第三方DataSource, 实现代码(以Druid为例)是这样:

package com.java.mybatis.datasource;

import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory;

import com.alibaba.druid.pool.DruidDataSource;

public class DruidDataSourceFactory extends UnpooledDataSourceFactory {
	public DruidDataSourceFactory() {
		this.dataSource = new DruidDataSource();
	}

}

然后就可以在config文件里面注入这个自定义的DataSourceFactory了,

<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="com.java.mybatis.datasource.DruidDataSourceFactory">
                <!--<property name="driverClassName" value="org.h2.Driver" />-->
                <property name="url" value="jdbc:h2:tcp://localhost/C:/java/h2/data/test;MODE=MYSQL;MVCC=TRUE;DB_CLOSE_DELAY=-1;" />
                <property name="username" value="admin" />
                <property name="password" value="admin" />
                <property name="validationQuery" value="select now()" />
                <property name="testWhileIdle" value="true" />
                <property name="testOnBorrow" value="false" />
                <property name="testOnReturn" value="false" />                            
		<!--<property name="filters" value="slf4j" />-->
                <property name="poolPreparedStatements" value="false" />
                <property name="maxOpenPreparedStatements" value="-1" />
            </dataSource>
        </environment>
    </environments>

相关推荐