Spring Boot之整合数据库
1、SpringBoot之JDBC
- 使用对应的启动器
<!-- jdbc的启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- 数据库的启动器-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
- 配置数据源
由于使用了对应的jdbc
启动器,所以springboot
自动装配了jdbc
对应的组件,我们可以直接使用,只需要配置好数据源即可。DataSourceAutoConfiguration
这个类就是jdbc
的自动装配类,它对应的properties
文件就是数据源的配置属性。
![image-20220108170526340](https://i-blog.csdnimg.cn/blog_migrate/03e260b14f8aae8291c2410c1c89cf37.png)
对应的配置文件为:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=tmerue&characterEncoding=utf-8&serveTimezone=UTC
password: 1234567
username: root
配置了数据源以后,springboot
自动封装了一个DataSource
组件到spring
容器中,这样就可以通过这个数据源获取数据库连接,连接到数据库中就可以进行数据库的操作。springboot
默认的数据源是HikariDataSource
@Autowired
DataSource dataSource;
@Test
void contextLoads() throws SQLException {
System.out.println(dataSource);
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
springboot
也封装了JdbcTemplate
这个类,直接通过这个已经封装好类进行数据库的操作。例如像下面:
@Autowired
JdbcTemplate jdbcTemplate;
@Test
void contextLoads() throws SQLException {
// sql语句
String sql = "select *from user";
// 将查询的结果封装到一个List中
List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
// 遍历结果
for (Object o:result) {
System.out.println(o);
}
}
2、SpringBoot之Druid
Druid数据源是阿里巴巴开源的一个数据库连接池,结合了c3p0、DBCP等其它数据连接池的众多优点,同时加入了日志监控系统。Druid可以很好监控DB连接池和SQL的执行情况,是一个很优秀的数据源。
2.1、druid使用步骤
- 导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
- 修改默认的数据源:只需要在配置文件中设置
type
属性即可。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=tmerue&characterEncoding=utf-8&serveTimezone=UTC
password: 1234567
username: root
type: com.alibaba.druid.pool.DruidDataSource
其他常用配置:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/mybatis?useUnicode=tmerue&characterEncoding=utf-8&serveTimezone=UTC
password: 1234567
username: root
type: com.alibaba.druid.pool.DruidDataSource
# 初始化大小
initial-size: 5
# 最小连接数
min-idle: 5
# 最大连接数
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存时间
min-evictable-idle-time-millis: 300000
# 打开 PSCache,并且指定每个连接上 PSCache 的大小
pool-prepared-statements: true
# 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙
# stat是监控的,wall是防火墙,log4j是日志
filters: stat,wall,log4j
2.2、druid日志监控
- 将配置文件注入到
DruidDataSource
中:
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource(){
return new DruidDataSource();
}
}
- 后台数据库监控的配置:
@Bean
public ServletRegistrationBean statViewServlet(){
// 第一个参数是一个类,第二个参数是访问路径,一般都是druid
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
HashMap<String, String> initParameters = new HashMap<>();
// 设置后台监控系统的登录密码,map的key只能这样写,不能改变
initParameters.put("loginUsername","xiaotanke");
initParameters.put("loginPassword","xiaotanke");
// 配置谁能访问(白名单),如果值是一个空串就是所有人就可以访问
initParameters.put("allow","127.0.0.1");
// 配置黑名单
initParameters.put("test","198.168.11.123");
bean.setInitParameters(initParameters);
return bean;
}
- 通过
localhost/druid
进行访问后台的数据库监控系统,需要先登录。
2.3、druid过滤器
// 过滤器
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(new WebStatFilter());
HashMap<String, String> initParameters = new HashMap<>();
// 这些资源就不进行统计
initParameters.put("exclusions","*.js,*.css,*.png,*.jpg,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
由于在SpringBoot
中内置了Servlet
容器,没有了web.xml
文件,但是可以通过这种方式来注册一个servlet
、filter
、listener
等。通过XXXRegistrationBean
,然后配置其属性,然后注入到Spring
容器中就可以使用了。
3、SpringBoot整合Mybatis
- 连接数据库并进行测试。
- 通过数据库中的字段,创建实体类。
- 编写
mapper
接口。
@Mapper // 这个注解表示这是一个mybatis的mapper接口
@Repository // 注入到Spring容器中
public interface UserMapper {
// 查询所有的用户
List<User> queryAllUser();
}
除了使用@Mapper
注解将这个接口标注为一个mybatis的mapper接口,也可以在主程序的使用@MapperScan
进行包扫描。这个注解对应的包下的所有接口在编译的时候就可以生成对应的实现类,可以配置多个包进行扫描。
@SpringBootApplication
@MapperScan({"com.xiaotanke.mapper","com.xiaotanke.mapper1"})
public class SpringBootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisApplication.class, args);
}
}
- 编写mapper对应的xml文件。
在resources文件夹下创建一个mapper文件,在这个文件下创建对应实体的mapper文件。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xiaotanke.mapper.UserMapper">
<select id="queryAllUser" resultType="User">
select *from mybatis.user
</select>
</mapper>
- mybatis与springboot的整合,编写配置文件。
# mybatis配置
mybatis:
# 别名包扫描
type-aliases-package: com.xiaotanke.entity
# mapper的注册,注意classpath:后面不要加 /
mapper-locations: classpath:mapper/*.xml
上面是两个基本的配置,可以配置的属性有很多,可以进入源码查看。
private String configLocation;
private String[] mapperLocations;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
private String typeHandlersPackage;
private boolean checkConfigLocation = false;
private ExecutorType executorType;
private Class<? extends LanguageDriver> defaultScriptingLanguageDriver;
private Properties configurationProperties;
@NestedConfigurationProperty
private Configuration configuration;
- 进行测试
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/query")
public List<User> queryAllUser(){
return userMapper.queryAllUser();
}
}