Spring Data
对于数据访问层,无论是SQL还是NOSQL,SpringBoot默认采用Spring Data的方式进行统一处理,添加大量自动配置,屏蔽了很多设置。引入各种xxxTemplate,xxxRepository来简化对数据访问层的操作,对我们来说只需要简单的设置即可。
1、操作数据库的步骤
- 创建一个项目
- 在pop.xml文件中加入相关的Jar包和数据量驱动以及数据库连接池
<!--SpringBoot的JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- mysql的连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<!--mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
- SpringBootv2.3.3.RELEASE,默认使用的是HiKariCP,以前的版本使用的Tomcat的数据源连接池,可以通过写一个配置类,更换数据源连接池(前提要在pop.xml文件中加入相关的连接池Jar包,以及在配置文件中加入数据源信息)
package com.database.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource dataSource() {
return new DruidDataSource();
}
}
在执行初始化数据源的时候,会将指定格式的SQL语句执行,
//执行在classpath路径下的schema.sql或者是schema-all.sql文件,或者也可以将SQL语句放在classpath下的文件夹下,在通过在配置文件中设置DataSource的schema即可
spring:
datasource:
schema:
- classpath:sql/department.sql #注意书写方式,-后面有一个空格,classpath:name.sql中间却没有空格
- classpath:sql/employee.sql
initialization-mode: always
class DataSourceInitializer {
private static final Log logger = LogFactory.getLog(DataSourceInitializer.class);
private final DataSource dataSource;
private final DataSourceProperties properties;
private final ResourceLoader resourceLoader;
......
private List<Resource> getScripts(String propertyName, List<String> resources, String fallback) {
if (resources != null) {
return getResources(propertyName, resources, true);
}
String platform = this.properties.getPlatform();
List<String> fallbackResources = new ArrayList<>();
fallbackResources.add("classpath*:" + fallback + "-" + platform + ".sql");
fallbackResources.add("classpath*:" + fallback + ".sql");
return getResources(propertyName, fallbackResources, false);
}
- SpringData特点
SPringData提供使用同意的挨批来对数据访问层进行操作,这主要是SpringData Commons项目来实现的,SpringData Commons使得在使用关系型和非关系型数据库都是基于Spring提供的统一的标准,(CURD,查询,排序和分页的功能)
- 统一的Repository接口
3、数据整合JPA
-
创建一个SpringBoot的maven项目,加上Spring JPA的依赖和JDBC,JavaWeb。
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.3.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.SpringDataJPA</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
-
创建一个实体类User
package com.springdatajpa.bean; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; @Entity @Table(name = "department") @JsonIgnoreProperties({"hibernateLazyInitializer","handler"}) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column private String name; @Column private String 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
-
创建一个接口,继承JPARepository
package com.springdatajpa.repository; import com.springdatajpa.bean.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User,Integer> { }
-
配置文件
spring: datasource: url: jdbc:mysql://localhost:3306/robin?useSSL=true&serverTimezone=UTC driver-class-name: com.mysql.cj.jdbc.Driver username: root password: root jpa: hibernate: ddl-auto: update show-sql: true
-
Controller类
package com.springdatajpa.controller; import com.springdatajpa.bean.User; import com.springdatajpa.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import java.util.Optional; @RestController public class UserController { @Autowired UserRepository userRepository; @GetMapping("user/{id}") public User getUser(@PathVariable("id") Integer id){ User one = userRepository.getOne(id); return one; } @GetMapping("/user") public User insertUser(User user){ User save = userRepository.save(user); return save; } }