如果我的博客能够帮到大家能够点个赞,关注一下,以后还会更新更过JavaWeb的高级技术,大家的支持就是我继续更新的动力。谢谢。
这篇博客记录一下使用SpringBoot整合SpringDataJPA,用于简化数据库访问,减少了Dao层的开放量,使得数据持久化更加方便简洁。
一、环境搭建
步骤:
- 创建Spring Boot工程
- 导入依赖
- 配置application.yml
- 创建实体和接口
- 测试
1.创建SpringBoot工程工程,大家都会,略
2.导入依赖:pom.xml
<?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 http://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.1.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.nyist</groupId> <artifactId>spring-boot-06-springdatajpa</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-06-springdatajpa</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <!--引入JPA依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--引入JDBC依赖--> <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> <!--引入Java驱动包--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--引入Druid--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
3.编写application.yml配置文件
spring: datasource: username: root password: root url: jdbc:mysql://localhost:3306/springdata_jdbc?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8 type: com.alibaba.druid.pool.DruidDataSource #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,logback-spring maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 #运行数据源建表语句 # schema: # - classpath:sql/department.sql # - classpath:sql/employee.sql #mybatis: # #指定 mybatis 全局配置文件 # config-location: classpath:mybatis/mybatis-config.xml # #指定 mybatis 的mapper 文件所在位置 # mapper-locations: classpath:mybatis/mapper/*.xml jpa: hibernate: #更新或者创建数据表 ddl-auto: update #在控制台打印SQL语句 show-sql: true
4.编写实体和接口
User实体类:
package com.nyist.SpringDataJPA.Entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; //这些标签或者更多标签的使用 请参考我之前的 几篇博客 SPringDataJPA 和 JPA //使用jpa 映射实体类 @Entity //告诉JPA这是一个实体类(和数据表映射的类) @Table(name = "jpa_user") @JsonIgnoreProperties(value = { "hibernateLazyInitializer", "handler" }) public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(name = "last_name",length = 50,nullable = false) private String lastName; @Column(name = "email",length = 210) private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public User() { } public User(String lastName, String email) { this.lastName = lastName; this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}'; } }
UserRepository接口:
package com.nyist.SpringDataJPA.Repository; import com.nyist.SpringDataJPA.Entity.User; import org.springframework.data.jpa.repository.JpaRepository; //集成JpaRepository 来完成对数据库的操作 public interface UserRepository extends JpaRepository<User,Integer> { }
5.测试
编写UserController.java
package com.nyist.SpringDataJPA.contorller; import com.nyist.SpringDataJPA.Entity.User; import com.nyist.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; @RestController public class UserController { @Autowired private 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 user1 = userRepository.save(user); return user1; } }
测试结果: