依赖
快捷创建SpringBoot时候选中,选择Spring Web,JDBC API 和 MySQL
配置数据库连接信息
spring:
datasource:
username: root
password: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
测试能否连接上数据库:
@SpringBootTest
class SpringbootDataJdbcApplicationTests {
//数据源
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
//是否获取到数据源
System.out.println(dataSource.getClass());
//获取一个连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}
}
springboot默认是使用com.zaxxer.hikari.HikariDataSource
作为数据源,2.0以下是用org.apache.tomcat.jdbc.pool.DataSource
作为数据源;
数据源的相关配置都在DataSourceProperties里面;
自动配置原理
jdbc的相关配置都在springframework\boot\autoconfigure\jdbc
包下
参考DataSourceConfiguration,根据配置创建数据源,默认使用Hikari连接池;可以使用spring.datasource.type指定自定义的数据源类型;
springboot默认支持的连池:
• org.apache.commons.dbcp2.BasicDataSource
• com.zaxxer.hikari.HikariDataSource
• org.apache.tomcat.jdbc.pool.DataSource
自定义数据源类型:
@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();
}
}
启动应用执行sql
SpringBoot在创建连接池后还会运行预定义的SQL脚本文件,具体参考org.springframework.boot.autoconfigure.jdbc.DataSourceInitializationConfiguration
配置类,
在该类中注册了dataSourceInitializerPostProcessor
下面是获取schema脚本文件的方法:
List<Resource> 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: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
schema.sql
:建表语句
data.sql
:插入数据
注意:项目每次启动都会执行一次sql
Springboot自动配置了JdbcTemplate操作数据库
整合Druid数据源
- 在 Spring Boot 项目中加入druid-spring-boot-starter依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
- 在配置文件中指定数据源类型
spring:
datasource:
username: root
password: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
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: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
#Spring Boot 默认是不注入这些属性值的,需要自己绑定
#druid 数据源专有配置
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
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
导入Log4j 的依赖
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Druid 后台监控
Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装 路由器 时,人家也提供了一个默认的 web 页面。
所以第一步需要设置 Druid 的后台管理页面,比如 登录账号、密码 等;配置后台管理;
@Configuration
public class DruidConfig {
//导入druid数据源
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
//配置Druid的监控
//1、配置一个管理后台的Servlet
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","root");
initParams.put("loginPassword","1022");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21");
bean.setInitParameters(initParams);
return bean;
}
}
访问地址:localhost:8080/druid
使用设置的账号密码进行登录可以进入后台监控页面:
配置 Druid web 监控 filter 过滤器
//配置 Druid 监控 之 web 监控的 filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
SpringBoot整合Mybatis
依赖关系
添加依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
配置数据库信息
spring:
datasource:
username: root
password: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
编写POJO,导入 Lombok
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
private Integer id;
private String name;
private double money;
}
创建mapper目录以及对应的 Mapper 接口
AccountMapper.java
@Mapper //表示这个类是mybatis的mapper类
@Repository //持久层
public interface AccountMapper {
List<Account> queryAllAccounts();
Account queryAccountById(int id);
int addAccount(Account account);
int deleteAccount(int id);
}
对应的Mapper映射文件
<?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.lwl.springboot.mapper.AccountMapper">
<select id="queryAllAccounts" resultType="Account">
select * from account1;
</select>
<select id="queryAccountById" parameterType="int" resultType="Account">
select * from account1 where id = #{id};
</select>
<update id="addAccount" parameterType="Account">
insert into account1 (id,name,money) values (#{id},#{name},#{money});
</update>
<update id="deleteAccount" parameterType="int">
delete from account1 where id=#{id};
</update>
</mapper>
同时在yaml配置文件中添加mybatis的相关配置:
spring:
datasource:
username: root
password: 1022
url: jdbc:mysql://localhost/test
driver-class-name: com.mysql.jdbc.Driver
initialization-mode: always
type: com.alibaba.druid.pool.DruidDataSource
#整合Mybatis
mybatis:
type-aliases-package: com.lwl.springboot.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
编写账户的AccountController 进行测试!
//@RestController = @Controller + @ResponseBody
@RestController
public class AccountController {
@Autowired
private AccountMapper accountMapper;
@GetMapping("/queryAllAccounts")
public List<Account> queryAllAccounts(){
List<Account> accounts = accountMapper.queryAllAccounts();
return accounts;
}
public Account queryAccountById(int id){
Account account = accountMapper.queryAccountById(id);
return account;
}
public int addAccount(Account account){
int i = accountMapper.addAccount(account);
return i;
}
public int deleteAccount(int id){
int i = accountMapper.deleteAccount(id);
return i;
}
}