001.Mybatis整合Druid连接池
1.在pom.xml中添加依赖
<!--Druid数据库连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.14</version> </dependency>
2.扩展一个数据源工厂(com.imooc.oa.datasource)
package com.imooc.oa.datasource; import com.alibaba.druid.pool.DruidDataSource; import org.apache.ibatis.datasource.unpooled.UnpooledDataSourceFactory; import javax.sql.DataSource; import java.sql.SQLException; public class DruidDataSourceFactory extends UnpooledDataSourceFactory { @Override public DataSource getDataSource() { try { ((DruidDataSource)this.dataSource).init(); } catch (SQLException throwables) { throw new RuntimeException(throwables); } return this.dataSource; } public DruidDataSourceFactory(){ this.dataSource = new DruidDataSource(); } }
3.修改mybatis-config.xml中dataSource
<?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> <settings> <!--开启驼峰命名转换 form_id -> formId--> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <environments default="dev"> <environment id="dev"> <transactionManager type="JDBC"/> <!--<dataSource type="POOLED">--> <dataSource type="com.imooc.oa.datasource.DruidDataSourceFactory"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/imooc_oa?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="197366"/> <property name="initialSize" value="10"/> <property name="maxActive" value="20"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mappers/test.xml"/> <mapper resource="mappers/user.xml"/> </mappers> </configuration>