首页 技术 正文
技术 2022年11月18日
0 收藏 744 点赞 4,867 浏览 8137 个字

一、前言

前边我们已经学些了开发的基本流程,最重要的一步来了,怎么样和数据库交互才是最重要的,毕竟没有数据那就相当于什么也没做,本文我们来学习使用springboot整合jdbc、mybatis、jpa等我们常用的数据库持久化技术。

二、整合jdbc

2.1 引入maven依赖

整合jdbc我们需要两个依赖,一个是starter依赖,一个是mysql驱动(访问数据库驱动肯定是比不可少的),starter中我们指定了要使用的数据源。

  <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

在application.yml或者application.properties中添加配置信息:

 spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/jdbctest?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver

2.2 测试数据库连接

在test中添加测试代码,来测试我们的数据库是否链接成功。

 @Autowired
DataSource dataSource; //....
@Test
public void jdbcTest() {
System.out.println(dataSource.getClass());
try {
System.out.println(dataSource.getConnection());
} catch (SQLException e) {
e.printStackTrace();
}
}

springboot整个jdbc,默认使用的是org.apache.tomcat.jdbc.pool.DataSource作为数据源,据源的相关配置都在DataSourceProperties里面。jdbc的自动配置原理在org.springframework.boot.autoconfigure.jdbc下。

2.3 使用数据

添加一个aciton,使用JdbcTemplate来查询数据:

 @Autowired
private JdbcTemplate jdbcTemplate; @RequestMapping("/query")
public List<Map<String, Object>> query() {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from `user`");
return list;
}

SpringBoot起飞系列-数据访问(九)

三、整合Druid数据源

这里我们整合Druid数据源,这是阿里巴巴的一个数据,整合之后我们可以跟踪sql日志,查询我们sql的执行情况。

3.1 添加pom依赖

 <!--引入druid数据源-->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>

在config下添加一个配置项DruidConfig.java:

 package com.example.demo.config; import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
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 javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map; @Configuration
public class DruidConfig { @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","admin");
initParams.put("loginPassword","123456");
initParams.put("allow","");//默认就是允许所有访问
initParams.put("deny","192.168.15.21"); bean.setInitParameters(initParams);
return bean;
} //2、配置一个web监控的filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean;
}
}

其中statViewServlet是数据库管理后台,便于我们查看数据sql监控,webStatFilter添加一个过滤来使Druid知道哪些请求(附带sql查询的请求)需要捕获到,以便于记录sql日志。

但是Druid后台默认使用的日志框架是log4j,和当前版本你的springboot的日志框架不一样,直接启动会报错,需要再添加一个依赖。参考:https://blog.csdn.net/lyn_kk/article/details/89086476

  <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>

3.2 数据源配置参数

在yml添加Druid数据源额外的参数:

 spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/jdbctest?serverTimezone=UTC&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver #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,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

启动访问 http://localhost:8080/druid/index.html可以登录sql管理后台来查看监控,当我们访问一次数据库就会有一次监控。

SpringBoot起飞系列-数据访问(九)

四、整合Mybatis

前边我们已经整个了jdbc和druid数据源,下面我们就来使用一个操作数据库的框架,我们之前所熟悉的mybatis也整合进来。

4.1 添加依赖

接上边的依赖配置,我们添加mybatis的依赖:

 <!--引入mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>

4.2 添加Mapper(注解版)

 package com.example.demo.mapper; import com.example.demo.domain.Department;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select; import java.util.List; @Mapper
public interface DepartmentMapper { @Select("select * from department")
List<Department> getAll(); @Select("select * from department where id=#{id}")
Department getById(Integer id); }

添加对应的实体:

 public class Department {
private Integer id;
private String name; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Department() { } public Department(Integer id, String name) {
this.id = id;
this.name = name;
} @Override
public String toString() {
return "Department{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

4.3 添加控制器访问

@RestController
@RequestMapping("/dept")
public class DepartmentController { @Autowired
DepartmentMapper departmentMapper; @GetMapping("list")
public Object getAll(){
return departmentMapper.getAll();
} @GetMapping("{id}")
public Object getById(@PathVariable("id") Integer id){
return departmentMapper.getById(id);
}
}

访问地址:http://localhost:8080/dept/1

SpringBoot起飞系列-数据访问(九)

使用@MapperScan注解指定包名,可以把该包下边的所有类注册为Mapper,使我们不用再每个类型写注解@Mapper。

 //使用MapperScan批量扫描所有的Mapper接口;
@MapperScan(value = "com.example.demo.mapper")
@SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
} }

4.4 Xml配置版

我们可以在类路径下添加传统的mybatis配置文件,并在application.yml添加如下配置就可以实现配置文件方式的mybatis。

mybatis:
config-location: classpath:mybatis/mybatis-config.xml 指定全局配置文件的位置
mapper-locations: classpath:mybatis/mapper/*.xml 指定sql映射文件的位置

五、整合SpringData JPA

5.1 什么是SpringData JPA

JPA(Java Persistence API)是Sun官方提出的Java持久化规范. 为Java开发人员提供了一种对象/关联映射工具来管理Java应用中的关系数据. 它的出现是为了简化现有的持久化开发工作和整合ORM技术. 结束各个ORM框架各自为营的局面。

JPA仅仅是一套规范,不是一套产品, 也就是说Hibernate, TopLink等是实现了JPA规范的一套产品。

Spring Data JPA是Spring基于ORM框架、JPA规范的基础上封装的一套JPA应用框架,是基于Hibernate之上构建的JPA使用解决方案,用极简的代码实现了对数据库的访问和操作,包括了增、删、改、查等在内的常用功能。

除此之外还有SpringData Redis、SpringData MongoDb。

SpringBoot起飞系列-数据访问(九)

5.2 引入依赖

  <!--整合jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency> <!--引入springdata jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

其中前两个都是访问数据库不可缺少的依赖,在整合mybatis的时候也有。

5.3 添加实体类

添加一个User类,添加相应注解,SpringData JPA会自动生成到数据库表。

 package com.example.demo.domain; import javax.persistence.*; @Entity
public class User { @Id //表名这是一个主键
@Column() //是数据库中的列,默认不写把属性名自动作为列,使用注解可以指定列明
@GeneratedValue(strategy = GenerationType.IDENTITY) //主键自增
private Integer id; @Column(name = "user_name",length = 50) //这是和数据表对应的一个列
private String name; private String email; public String getEmail() {
return email;
} public void setEmail(String email) {
this.email = email;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}

5.4 添加一个仓储

 package com.example.demo.repository; import com.example.demo.domain.User;
import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }

只要继承了JpaRepository<User,Integer>就行了,里边有封装好自带的访问数据库的方法。

5.5 添加一个控制器

 @RestController
public class UserController { @Autowired
UserRepository userRepository; @GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id){
Optional<User> optional = userRepository.findById(id);
return optional.get();
} @GetMapping("/user")
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}
}

里边有一个插入的方法和一个获取的方法,我们可以先插入在访问获取方法。

访问:http://localhost:8080/user?name=dsff&email=526457385@qq.com来插入数据,访问:http://localhost:8080/user/1来获取数据。

六、总结

以上就是springboot对数据库访问的整合了,基本上学到这里就可以完全的使用springboot进行开发了,其他的一些细节问题会开发过程中遇见的时候再进行学习就行了。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,084
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,559
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,408
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,181
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,818
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,901