mybatis 自定义 datasource

  • 实现 org.apache.ibatis.datasource.DataSourceFactory 接口
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.datasource.DataSourceFactory;
import javax.sql.DataSource;
import java.util.Properties;

public class MyDataSource implements DataSourceFactory {
    private final DruidDataSource dataSource = new DruidDataSource();
    @Override
    public void setProperties(Properties props) {
        dataSource.configFromPropety(props);
    }
    @Override
    public DataSource getDataSource() {
        return dataSource;
    }
}
  • 修改 mybatis 配置文件

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"/>
            
            <dataSource type="com.example.datasource.MyDataSource">
                <property name="druid.driverClass" value="com.mysql.cj.jdbc.Driver"/>
                <property name="druid.url" value="jdbc:mysql:///mybatis?serverTimezone=Asia/Shanghai"/>
                <property name="druid.username" value="root"/>
                <property name="druid.password" value="root"/>
                <property name="druid.testWhileIdle" value="true"/>
            dataSource>
        environment>
    environments>
    <mappers>
        <package name="mapper"/>
    mappers>
configuration>

你可能感兴趣的:(java,mybatis,java)