首页 > 其他 > 详细

Mybatis数据连接池的配置

时间:2021-03-27 12:37:01      阅读:26      评论:0      收藏:0      [点我收藏+]

1.首先创建项目和各个文件,如图所示:

技术分享图片

2.配置相关数据库连接

jdbc.properties中加入

1 db.driver=com.mysql.jdbc.Driver
2 db.url=jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
3 db.username=root
4 db.password=xiaopan
5 db.maxActive=10
6 db.initialSize=2

注意,用户名和密码,还有数据库名换成你自己的。

技术分享图片

 

 3.创建MybaticConfig数据库配置类。

 

package com.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:jdbc.properties")
public class MybatisConfig {
@Value("${db.driver}") String driver;
    @Value("${db.url}") String url;
    @Value("${db.username}") String username;
    @Value("${db.password}") String password;
    @Value("${db.maxActive}") int maxActive;
    @Value("${db.initialSize}") int initialSize;

    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(maxActive);
        dataSource.setInitialSize(initialSize);
        return dataSource;
    }
}

 

 

 

技术分享图片

 

 4.进行数据库连接测试

--创建一个测试类TestCase技术分享图片

 

 --在测试类中写入以下代码

import com.config.MybatisConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

public class TestCase {
    AnnotationConfigApplicationContext ctx;
    @Before
    public void init(){
        ctx= new AnnotationConfigApplicationContext(MybatisConfig.class);
    }
    @After
    public void destroy(){
        ctx.close();
    }
    @Test
    public void testDataSource(){
        DataSource ds = ctx.getBean("dataSource",DataSource.class);
        String sql = "select ‘hello world‘";
        try(Connection conn = ds.getConnection()){
            Statement s = conn.createStatement();
            ResultSet rs = s.executeQuery(sql);
            while(rs.next()){
                System.out.println(rs.getString(1));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

技术分享图片

 

 点击测试,出现对应的hello world在控制台中。

 

Mybatis数据连接池的配置

原文:https://www.cnblogs.com/bulter/p/14584952.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!