跳转到目录
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
测试能否连接上数据库
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
springboot默认是使用com.zaxxer.hikari.HikariDataSource
作为数据源,2.0以下是用org.apache.tomcat.jdbc.pool.DataSource作为数据源;
数据源的相关配置都在DataSourceProperties
里面;
jdbc的相关配置都在org.springframework.boot.autoconfigure.jdbc
包下
参考DataSourceConfiguration
,根据配置创建数据源,默认使用Hikari
连接池;可以使用spring.datasource.type指定自定义的数据源类型;
springboot默认支持的连接池:
自定义数据源类型:
@Configuration(
proxyBeanMethods = false
)
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
@Bean
DataSource dataSource(DataSourceProperties properties) {
//使用DataSourceBuilder创建数据源,利用反射创建响应type的数据源,并且绑定相关属性
return properties.initializeDataSourceBuilder().build();
}
}
SpringBoot在创建连接池后还会运行预定义的SQL脚本文件,具体参考org.springframework.boot.autoconfigure.jdbc.DataSourceInitializationConfiguration
配置类,在该类中注册了dataSourceInitializerPostProcessor
下面是获取schema脚本文件的方法
List scripts = this.getScripts(“spring.datasource.schema”, this.properties.getSchema(), “schema”);
可以看出,如果我们没有在配置文件中配置脚本的具体位置,就会在classpath下找schema-all.sql
和schema.sql
platform获取的是all,platform可以在配置文件中修改
具体查看createSchema()
方法和initSchema()
方法
initSchema()方法获取的是data-all.sql
,data.sql
我们也可以在配置文件中配置sql文件的位置
spring:
datasource:
schema:
- classpath:department.sql
- 指定位置
测试:
在类路径下创建schema.sql
,运行程序查看数据库是否存在该表
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`departmentName` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
程序启动后发现表并没有被创建,DEBUG查看以下,发现在运行之前会有一个判断
上面方法也不知道在干什么,反正就是只要是NEVER
和EMBEDDED
就为true,而DataSourceInitializationMode枚举类中除了这两个就剩下ALWAYS了,可以在配置文件中配置为ALWAYS
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/spring_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
schema.sql
:建表语句
data.sql
:插入数据
注意:项目每次启动都会执行一次sql
跳转到目录
选择哪个数据库连接池:
不选择 C3P0 的原因:
不选择 DBCP2 的原因:
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.20version>
dependency>
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 数据源更改为druid
type: com.alibaba.druid.pool.DruidDataSource
@SpringBootTest
class SpringbootJdbcApplicationTests {
@Autowired
private DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource.getClass());
System.out.println(dataSource.getConnection());
}
}
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 数据源更改为druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 连接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: stat,wall,slf4j
方式一 : 通过配置后台监控的Servlet
和Filter
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource() {
return new DruidDataSource();
}
// 配置Druid的监控(除了下面的方式,也可以在yml中配置)
//1. 配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet() {
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "root");
initParams.put("loginPassword", "1111");
initParams.put("allow", ""); // 默认就是允许所有访问
// initParams.put("deny", "这里写要拒绝访问的地址");
registrationBean.setInitParameters(initParams);
return registrationBean;
}
//2. 配置一个监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new WebStatFilter());
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
registrationBean.setInitParameters(initParams);
registrationBean.setUrlPatterns(Arrays.asList("/*"));
return registrationBean;
}
}
方式二: 通过全局配置文件yml
方式
spring:
datasource:
username: root
password: 1111
url: jdbc:mysql://localhost:3306/springboot_jdbc
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
# schema:
# - classpath:department.sql
# 数据源更改为druid
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 连接池配置
# 配置初始化大小、最小、最大
initial-size: 1
min-idle: 1
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 3000
validation-query: SELECT 1 FROM DUAL
test-on-borrow: false
test-on-return: false
test-while-idle: true
pool-prepared-statements: true
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
filters: stat,wall,slf4j
# 配置web监控,默认配置也和下面相同(除用户名密码,enabled默认false外),其他可以不配
web-stat-filter:
enabled: true
url-pattern: /*
exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
enabled: true
url-pattern: /druid/*
login-username: admin
login-password: root
allow: 127.0.0.1
后台页面,访问http://localhost:8080/druid/login.html
这样就可以监控我们通过Druid连接池来进行的请求!