SpringBoot整合阿里Druid数据源及Spring-Data-Jpa

https://mp.weixin.qq.com/s?__biz=MzU0MDEwMjgwNA==&mid=2247484669&idx=1&sn=f28a9ae8067af39c8d9406b7842c7751&chksm=fb3f1d06cc489410bc5bc5ad1a857bc239962539bd51a239f406644055ef7fcbdc7975288899&scene=0&key=f90f52b171784d83da3e317c903ae4bebd202ad3353a3030ce03cbe404e2527b0b1d0761a9029f0eee109af1a66f4d9f15384196a9686dca43c689473de1369b24c20156685eedd7f09328bbcc55459c&ascene=1&uin=MjgwMTEwNDQxNg%3D%3D&devicetype=Windows-QQBrowser&version=6103000b&lang=zh_CN&pass_ticket=Pbtuc%2B57vDHGrUKlz7gN6m3DE%2BsmcWebe008LyFC7dD5%2B8zGrdL8USzjdzIexKLI

最近开辟了一个新项目,因为初期考虑到可能会调整数据库的风险,所以orm,在设计之初就考虑为Spring Data Jpa, 以下是工程data层数据,整体是参照配置多数据源的方案,进行配置的

目录

  • 因为阿里数据源 Druid

  • 整合数据源及其他事务配置

  • pom依赖

整合事务

  1. @EnableAutoConfiguration

  2. @SpringBootApplication

  3. @EnableTransactionManagement

  4. @ComponentScan(basePackages = {"com.inn.developer"})

  5. public class CodeApplication {

  6.    public static void main(String[] args) {

  7.        new SpringApplicationBuilder().web(true).sources(CodeApplication.class).run(args);

  8.    }

  9. }

创建 DruidProperties配置

  1. @Data

  2. @AllArgsConstructor

  3. @NoArgsConstructor

  4. @ConfigurationProperties(prefix = "druid")

  5. public class DruidProperties {

  6. ...

数据库参数可以参考:

参数 默认值 解释
initialSize 3 初始化配置
minIdle 3 最小连接数
maxActive 15 最大连接数
maxWait 5000 获取连接超时时间(单位:ms)
timeBetweenEvictionRunsMillis 90000 连接有效性检测时间(单位:ms)
testOnBorrow false 获取连接检测
testOnReturn false 归还连接检测
minEvictableIdleTimeMillis 1800000 最大空闲时间(单位ms)
testWhileIdle true 在获取连接后,确定是否要进行连接空间时间的检查
     
  • 配置说明:

   
     
1:minEvictableIdleTimeMillis(最大空闲时间):默认为30分钟,配置里面不进行设置。    

2:testOnBorrow ,testOnReturn 默认为关闭,可以设置为不配置。

3:testWhileIdle(在获取连接后,确定是否要进行连接空闲时间的检查)。默认为true。配置里面不再进行设置。

  • 流程说明:

    1:在第一次调用connection的时候,才会进行 initialSize的初始化。

    2:心跳检测时间线程,会休眠timeBetweenEvictionRunsMillis时间,然后只对(没有borrow的线程 减去 minIdle)的线程进行检查,如果空闲时间大于minEvictableIdleTimeMillis则进行close。

    3:testWhileIdle必须设置为true,在获取到连接后,先检查testOnBorrow,然后再判定testwhileIdle,如果连接空闲时间大于timeBetweenEvictionRunsMillis,则会进行心跳检测。

    4:不需要配置validationQuery,如果不配置的情况下会走ping命令,性能更高。

    5:连接保存在数组里面,获取连接的时候,获取数组的最后一位。在imeBetweenEvictionRunsMillis时是从前往后进行检查连接的有效性。

配置数据源及hibernate适配

数据源对象创建还是和之前一样, 笔者不太喜欢xml的方式,所以还是采用配置类

DruidAutoJpaConfiguration

  1. @Configuration

  2. @EnableConfigurationProperties(DruidProperties.class)//开启属性注入,通过@autowired注入

  3. @ConditionalOnClass(DruidDataSource.class)//表示对应的类在classpath目录下存在时,才会去解析对应的配置文件

  4. @ConditionalOnProperty(prefix = "druid", name = "url")

  5. @EnableJpaRepositories(basePackages = "com.inn.developer.model.dao",transactionManagerRef = "jpaTransactionManager", entityManagerFactoryRef = "localContainerEntityManagerFactoryBean")

  6. public class DruidAutoJpaConfiguration {

  7.    @Autowired

  8.    private DruidProperties properties;

  9.    @Bean(name = "druidDataSource")

  10.    @Primary

  11.    public DataSource dataSource() {

  12.        DruidDataSource dataSource = new DruidDataSource();

  13.        dataSource.setUrl(properties.getUrl());

  14.        dataSource.setUsername(properties.getUsername());

  15.        dataSource.setPassword(properties.getPassword());

  16.        dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());

  17.        if (properties.getInitialSize() > 0) {

  18.            dataSource.setInitialSize(properties.getInitialSize());

  19.        }

  20.        if (properties.getMinIdle() > 0) {

  21.            dataSource.setMinIdle(properties.getMinIdle());

  22.        }

  23.        if (properties.getMaxActive() > 0) {

  24.            dataSource.setMaxActive(properties.getMaxActive());

  25.        }

  26.        dataSource.setTestOnBorrow(properties.isTestOnBorrow());

  27.        dataSource.setValidationQuery("select version()");

  28.        try {

  29.            dataSource.init();

  30.        } catch (SQLException e) {

  31.            throw new RuntimeException(e);

  32.        }

  33.        return dataSource;

  34.    }

  35.    /**

  36.     * hibernate 适配器,定制方言为mysql,并打印sql

  37.     *

  38.     * @return

  39.     */

  40.    @Bean(name = "hibernateJpaVendorAdapter")

  41.    @Primary

  42.    public HibernateJpaVendorAdapter hibernateJpaVendorAdapter() {

  43.        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();

  44.        hibernateJpaVendorAdapter.setShowSql(true);

  45.        hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");

  46.        return hibernateJpaVendorAdapter;

  47.    }

  48.    @Bean(name = "localContainerEntityManagerFactoryBean")

  49.    @Primary

  50.    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(@Qualifier("druidDataSource") DataSource dataSource

  51.            ,@Qualifier("hibernateJpaVendorAdapter") HibernateJpaVendorAdapter hibernateJpaVendorAdapter) {

  52.        LocalContainerEntityManagerFactoryBean local = new LocalContainerEntityManagerFactoryBean();

  53.        local.setDataSource(dataSource);

  54.        local.setJpaVendorAdapter(hibernateJpaVendorAdapter);

  55.        local.setPackagesToScan("com.inn.developer.model.domain");

  56.        Properties properties = new Properties();

  57.        properties.put("hibernate.format_sql", true);

  58.        properties.put("hibernate.hbm2ddl.auto", "update");

  59.        local.setJpaProperties(properties);

  60.        return local;

  61.    }

  62.    @Bean(name = "jpaTransactionManager")

  63.    @Primary

  64.    public JpaTransactionManager jpaTransactionManager(@Qualifier("localContainerEntityManagerFactoryBean") LocalContainerEntityManagerFactoryBean entityManagerFactoryBean) {

  65.        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();

  66.        EntityManagerFactory object = entityManagerFactoryBean.getObject();

  67.        jpaTransactionManager.setEntityManagerFactory(object);

  68.        return jpaTransactionManager;

  69.    }

pom依赖

  1. <dependency>

  2.            <groupId>mysql</groupId>

  3.            <artifactId>mysql-connector-java</artifactId>

  4.        </dependency>

  5.        <dependency>

  6.            <groupId>org.springframework.boot</groupId>

  7.            <artifactId>spring-boot-starter-data-jpa</artifactId>

  8.        </dependency>

  9.         <dependency>

  10.            <groupId>org.projectlombok</groupId>

  11.            <artifactId>lombok</artifactId>

  12.            <version>1.16.6</version>

  13.            <scope>provided</scope>

  14.        </dependency>

  15.          <dependency>

  16.            <groupId>com.alibaba</groupId>

  17.            <artifactId>druid</artifactId>

  18.            <version>1.0.11</version>

  19.        </dependency>

  20.         <!--依赖Spring 4.3.6之core、context、aop、beans、tx、orm和spring data commons -->

  21.        <dependency>

  22.            <groupId>org.springframework.data</groupId>

  23.            <artifactId>spring-data-jpa</artifactId>

  24.            <version>1.11.3.RELEASE</version>

  25.        </dependency>

  26.        <!--hibernate 实现JPA的框架 -->

  27.        <dependency>

  28.            <groupId>org.hibernate</groupId>

  29.            <artifactId>hibernate-entitymanager</artifactId>

  30.            <version>5.2.5.Final</version>

  31.        </dependency>

  32.        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->

  33.        <dependency>

  34.            <groupId>org.hibernate</groupId>

  35.            <artifactId>hibernate-core</artifactId>

  36.            <version>5.2.11.Final</version>

  37.        </dependency>

  38.        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-annotations -->

  39.        <dependency>

  40.            <groupId>org.hibernate</groupId>

  41.            <artifactId>hibernate-annotations</artifactId>

  42.            <version>3.5.6-Final</version>

  43.        </dependency>

招人:数心,造化心数奇;用心等你...

上一篇:webflux 与swagger2.x

转载于:https://www.cnblogs.com/bigben0123/p/9364312.html

SpringBoot整合阿里Druid数据源及Spring-Data-Jpa相关推荐

  1. Springboot 系列(十)使用 Spring data jpa 访问数据库

    前言 Springboot data jpa 和 Spring jdbc 同属于 Spring开源组织,在 Spring jdbc 之后又开发了持久层框架,很明显 Spring data jpa 相对 ...

  2. 【夏目鬼鬼分享】springboot搭建阿里Druid数据源监控

    Druid介绍 Druid是一个专为大型数据集上的高性能切片和OLAP分析而设计的数据存储.Druid最常用作为GUI分析应用程序提供动力的数据存储,或者用作需要快速聚合的高度并发API的后端. Dr ...

  3. 使用H2Database+Druid连接池+Spring Data JPA+Ehcache实现CRUD操作

    前言 注:本篇为纯实践篇,主要用于技术整合,介绍如何搭建一个完整全面的Web项目.如果对于技术原理还不了解的童鞋可点击下方链接,学习后在来~ H2数据库教程:H2数据库入门 缓存使用教程:在Sprin ...

  4. Spring Boot 2.x基础教程:使用Spring Data JPA访问MySQL

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 作者 | 翟永超 来源 | http://blog.di ...

  5. Spring Boot 2.x基础教程:使用Spring Data JPA访问MySQL我们得从哪入手

    在数据访问这章的第一篇文章<Spring中使用JdbcTemplate访问数据库> 中,我们已经介绍了如何使用Spring Boot中最基本的jdbc模块来实现关系型数据库的数据读写操作. ...

  6. Spring Boot 应用系列 1 -- Spring Boot 2 整合Spring Data JPA和Druid,双数据源

    最近Team开始尝试使用Spring Boot + Spring Data JPA作为数据层的解决方案,在网上逛了几圈之后发现大家并不待见JPA,理由是(1)MyBatis简单直观够用,(2)以Hib ...

  7. spring boot socket长连接_springboot 整合阿里 druid 数据库连接池实战

    情景 web 开发中连接数据库基本是必须的,阿里的 druid 是一款非常优秀的开源数据库连接池工具. 本文将介绍一下如何使用 springboot 整合 druid 数据源. 快速开始 maven ...

  8. 第九章SpringBoot整合Spring Data JPA

    目录 1 概述 2 Spring Data JPA整合 2.1 pom文件 2.2 配置文件 2.3 实体类 2.4 Dao接口 2.5 启动类 2.6 编写测试类 3 Spring Data JPA ...

  9. springboot整合hibernate_峰哥说技术系列-17 .Spring Boot 整合 Spring Data JPA

    今日份主题 Spring Boot 整合 Spring Data JPA JPA(Java Persistence API)是用于对象持久化的 API,是Java EE 5.0 平台标准的 ORM 规 ...

最新文章

  1. Python协方差矩阵处理脑电数据
  2. [Spring cloud 一步步实现广告系统] 16. 增量索引实现以及投送数据到MQ(kafka)
  3. MapReduce数据连接
  4. Python应用实战案例-Python协程管理精讲万字长文(建议收藏)
  5. 牛客竞赛语法入门班数组栈、队列和stl习题【未完成】
  6. linux重置网络协议,Linux 内核网络协议栈 ------ tcp_ack 函数处理接收到的ACK包之后 ....
  7. java 实现超时_如何实现带有超时的Runnable? - java
  8. 如何利用bat在同一个IE用多个选项卡的方式打开多个网址? 如何利用bat在同一个IE用多个选项卡的方式打开多个网址? 我的网址是这样的http://www.xags.gov.cn:8003/gga
  9. Eclipce Luna 离线安装ADT23
  10. 如何破解几乎所有的求职面试
  11. RTP封装G711源代码
  12. JZOJ 3.10 1539——三条直线
  13. 最小化——最速下降法matlab实现
  14. js 对象和回调函数
  15. 浅谈如何做好项目管理
  16. uc打开html文件是空的,UC浏览器中打开不出现主页的解决方法
  17. android中禁止输入表情符号,Android EdText编辑框禁止输入表情符号(使用正则表达式)...
  18. 斯人已去,因荣永存(下)
  19. 能力不够,你就态度好点
  20. Java并发包concurrent——ConcurrentHashMap

热门文章

  1. 零基础Python学习方法,Python入门必读
  2. 《是碰巧还是执着?python所阅读的每一场知识点,唯一的共同点就是——参赛选手中,有python之socket编程!》
  3. 韩顺平 php 聪明的小猫代码,聪明的小猫作文150字
  4. jsp mysql环境_MySQL在JSP环境下的操作应用
  5. fiddler汉化版可以改成英文吗_可以把推拉门改成平开窗吗?推拉门和平开窗哪个更好?...
  6. 【OpenCV】OpenCV函数精讲之 -- 通道分离:split()函数
  7. 传感器的特性及性能参数
  8. Python数据分析模块 | pandas做数据分析(二):常用预处理操作
  9. php把时间戳改为时间格式,php怎么把时间格式转换为时间戳?
  10. 30个HTML标签,10.30 html标签