首先在ITEye上面看到一个同标题文章,在此说明,此文并非转载自 http://iintothewind.iteye.com/blog/2069522 ,因为这篇文章根本就是错误的,照着上面做,工程可以跑,但是dataSource根本不是druid的
首先说明一下我使用的各个软件版本:
druid版本:1.0.8
<!-- mysql数据库连接池 pool --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.8</version> </dependency>
mybatis版本:3.2.8
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency>
MyBatis在非Spring环境下第三方DataSource设置 ,代码如下:
mybatis.xml:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="userDefine"> <environment id="userDefine"> <transactionManager type="JDBC" /> <!-- 配置数据库连接信息 --> <dataSource type="com.chenjun.mysite.common.MyselfDefineDataSourceFactory"> <property name="driverClass" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/site-aliyun"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappings/modules/sys/userDao.xml"/> </mappers> </configuration>
MyselfDefineDataSourceFactory是 ,自定义datasourceFactory ,作为type属性给上面的mybatis.xml文件
package com.chenjun.mysite.common; import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory; import com.alibaba.druid.pool.DruidDataSource; public class MyselfDefineDataSourceFactory extends UnpooledDataSourceFactory { public MyselfDefineDataSourceFactory() { this.dataSource = new DruidDataSource(); } }
验证结论:
public class UserDao { private static final String NAME_SPACE = "com.chenjun.mysite.entity.User"; public User test1(){ User user = new User(); SqlSessionFactory sqlSessionFactory; try { sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis.xml"),"userDefine"); SqlSession session = sqlSessionFactory.openSession();
System.out.println("class="+session.getConfiguration().getEnvironment().getDataSource().getClass().getName()); DataSource ds = session.getConfiguration().getEnvironment().getDataSource(); if(ds instanceof DruidDataSource){ System.out.println("Yes"); }else{ System.out.println("No"); } user = session.selectOne(NAME_SPACE+"."+"test1"); } catch (IOException e) { e.printStackTrace(); } return user; } }
最后输出
class=com.alibaba.druid.pool.DruidDataSource
Yes
15:55:09.817 [qtp2104354711-23] DEBUG org.apache.ibatis.transaction.jdbc.JdbcTransaction - Opening JDBC Connection
15:55:09.850 [qtp2104354711-23] INFO com.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited
这才是集成druid的正确打开方式!!!