spring-data-jpa快速入门(一)——整合阿里Druid

一、概述

  官网:https://projects.spring.io/spring-data-jpa/

  1.什么是spring-data-jpa

  Spring Data JPA, part of the larger Spring Data family, makes it easy to easily implement JPA based repositories. This module deals with enhanced support for JPA based data access layers. It makes it easier to build Spring-powered applications that use data access technologies.

  Spring Data JPA是Spring Data系列的一部分,可以轻松实现基于JPA的存储库。该模块处理对基于JPA的数据访问层的增强支持。这使得构建使用数据访问技术的Sprin应用程序变得更加容易。

  2.spring-data-jpa有什么

  spring-data-jpa快速入门(一)——整合阿里Druid

  继承关系图:

  spring-data-jpa快速入门(一)——整合阿里Druid

二、起步

    基本的HelloWorld完整代码在springboot快速入门中已有介绍,参考这里

    不过由于当时没有引入数据库连接池,这里对它进行改进,使用阿里巴巴druid作为数据源,添加监控

    阿里Druidhttps://github.com/alibaba/druid

    整合参考:https://www.jianshu.com/p/e84e2709f383

    1.引入依赖

<!-- alibaba-druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>

  // 其他依赖请参见前文

  2.在application.yml配置文件中配置数据源

    官方参考配置:点击查看

    各配置项解析https://www.cnblogs.com/lmaplet/p/6170105.html

spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/sakila
username: root
password: root
# druid配置项,默认spring-boot不支持,故需要config类来解析
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
filters: stat,wall,log4j
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
jpa:
hibernate:
ddl-auto: update
show-sql: true

  3.添加Druid配置类

package com.example.demo.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary; import javax.sql.DataSource;
import java.sql.SQLException; /**
* 阿里Druid配置类
*
* @author zcc ON 2018/2/11
**/
@Configuration
public class DruidConfig {
private static final Logger log = LoggerFactory.getLogger(DruidConfig.class); @Value("${spring.datasource.url}")
private String dbUrl; @Value("${spring.datasource.username}")
private String username; @Value("${spring.datasource.password}")
private String password; @Value("${spring.datasource.driverClassName}")
private String driverClassName; @Value("${spring.datasource.initialSize}")
private int initialSize; @Value("${spring.datasource.minIdle}")
private int minIdle; @Value("${spring.datasource.maxActive}")
private int maxActive; @Value("${spring.datasource.maxWait}")
private int maxWait; @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis; @Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis; @Value("${spring.datasource.validationQuery}")
private String validationQuery; @Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle; @Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow; @Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn; @Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements; @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize; @Value("${spring.datasource.filters}")
private String filters; @Value("{spring.datasource.connectionProperties}")
private String connectionProperties; @Bean
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
log.info("----------- druid datasource ----------");
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName); 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);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
e.printStackTrace();
}
datasource.setConnectionProperties(connectionProperties); return datasource;
} @Bean
public ServletRegistrationBean registrationBean() {
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet()); // 添加初始化参数:initParams
servletRegistrationBean.addUrlMappings("/druid/*");
// 白名单
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// 黑名单
servletRegistrationBean.addInitParameter("deny", "192.168.0.101");
// 登录查看信息的账号密码.
servletRegistrationBean.addInitParameter("loginUsername", "admin");
servletRegistrationBean.addInitParameter("loginPassword", "123456");
// 可重置数据.
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
} @Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
// 添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
}

  其中,@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean

       @Primary  //在同样的DataSource中,首先使用被标注的DataSource

  4.配置QueryDsl

    后面介绍JPA进行补充!

  5.测试

    正常调试项目接口(使用IDEA自带插件或者Postman)

    查看监控页面(监控页面由Druid生成)

      访问:127.0.0.1:8080/druid/login.html

      spring-data-jpa快速入门(一)——整合阿里Druid

    其中,IP白名单(为空则为所有)与监控登录信息在Druid配置中!

上一篇:Android实战项目——家庭记账本(七)


下一篇:python 之sqlalchemy many to many