spring boot 加入库连接池(alibaba druid 数据)

前言

上一遍只是简单的说明了怎么加入Mybatis,但这远远还是不够,我们还需要加入数据库连池来帮助我们来管理数据库连接。

1、加spring boot druid 依赖

<dependency>
 <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.8</version>
</dependency>

注意,你的spring boot版本,如果是spring boot 是2.x 以上那么druid-spring-boot-starter的版本号也要相应的比较高的版本,在引入druid-spring-boot-starter依赖的时候,我刚开始引入的比较低的版本1.1.5结果执行测试类时一直报错:
这里写图片描述
在升级完druid的版本号后,就不再报错了。

2、durid配置文件

application.properties文件中添加配置

#连接池的配置信息
## 初始化大小,最小,最大
spring.datasource.druid.initialSize=5
spring.datasource.druid.minIdle=5
spring.datasource.druid.maxActive=20
## 配置获取连接等待超时的时间
spring.datasource.druid.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.druid.minEvictableIdleTimeMillis=300000
spring.datasource.druid.validationQuery=SELECT 1 FROM DUAL
spring.datasource.druid.testWhileIdle=true
spring.datasource.druid.testOnBorrow=false
spring.datasource.druid.testOnReturn=false
spring.datasource.druid.poolPreparedStatements=true
spring.datasource.druid.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.druid.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.druid.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

3、添加数据源类

@Configuration
//在这里添加MapperScan 扫包,在启动类中就不用再添加了
@MapperScan(basePackages = "com.clockbone.dao",sqlSessionFactoryRef = "sqlSessionFactory")
public class DruidDatabaseConfiguration {

    /*@Value(value = "spring.datasource.url")
    private String dbUrl;
    @Value(value = "spring.datasource.username")
    private String username;
    @Value(value = "spring.datasource.password")
    private String password;
    @Value(value = "spring.datasource.driver-class-name")
    private String driverClassName;
    @Value(value = "spring.druid.initialSize")
    private int initialSize;
    @Value(value = "spring.druid.minIdle")
    private int minIdle;
    @Value(value = "spring.druid.maxActive")
    private int maxActive;
    @Value(value = "spring.druid.maxWait")
    private int maxWait;
    @Value(value = "spring.druid.timeBetweenEvictionRunsMillis")
    private int timeBetweenEvictionRunsMillis;
    @Value(value = "spring.druid.minEvictableIdleTimeMillis")
    private int minEvictableIdleTimeMillis;
    @Value(value = "spring.druid.validationQuery")
    private String validationQuery;
    @Value(value = "spring.druid.testWhileIdle")
    private boolean testWhileIdle;
    @Value(value = "spring.druid.testOnBorrow")
    private boolean testOnBorrow;
    @Value(value = "spring.druid.testOnReturn")
    private boolean testOnReturn;
    @Value(value = "spring.druid.poolPreparedStatements")
    private boolean poolPreparedStatements;
    @Value(value = "spring.druid.maxPoolPreparedStatementPerConnectionSize")
    private int maxPoolPreparedStatementPerConnectionSize;
    @Value(value = "spring.druid.filtersl")
    private String filters;
    @Value(value = "spring.druid.connectionProperties")
    private String connectionProperties;*/

    @Bean
    //统一配置名前缀,可以减少上面配置代码
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DruidDataSource dataSource() throws SQLException {
        DruidDataSource datasource = new DruidDataSource();
        /*datasource.setUrl(this.dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);

        //configuration
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);    datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
        datasource.setFilters(filters);*/
        return datasource;
    }

    @Bean
    public DataSourceTransactionManager transactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setDataSource(dataSource);  
              sessionFactory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        /*PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        sessionFactory.setPlugins(new Interceptor[]{pageHelper});*/

        return sessionFactory.getObject();
    }

}

4、mapper类及文件

//UserMapper.java

//@Mapper  可以去掉这个注解了
public interface UserMapper {
    @Select("SELECT ID,USER_ID as userId,USER_NAME as userName FROM Userinfo where id=#{id}")
    User getUserInfo(long id);
    User selectByPrimaryKey(Long id);
}

//UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.clockbone.dao.UserMapper" >

    <resultMap id="BaseResultMap" type="com.clockbone.model.User" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="user_id" property="userId" jdbcType="VARCHAR" />
    </resultMap>

    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" >
        select
        user_id as userId,user_name userName,id
        from User
        where id = #{id}
    </select>
</mapper>
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lh87270202/article/details/79964819
文章标签: spring boot
个人分类: java spring
上一篇spring boot 整合mybatis
想对作者说点什么? 我来说一句

spring cloud与spring boot实战

-

学院

1970年01月01日 08:00

没有更多推荐了,返回首页

不良信息举报

spring boot 加入库连接池(alibaba druid 数据)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭