SpringBoot集成Spring Data JPA
项目环境
- IDEA 2019.1
- SpringBoot 2.1.5
- Gradle 4.10
操作步骤
创建数据库
- 创建数据库
microservice
,后续会使用
新增配置和依赖
- 在
build.gradle
中添加要使用的依赖包,如下所示:
//数据库连接使用druid连接池
compile('org.springframework.boot:spring-boot-starter-data-jpa'){
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
compile group: 'com.alibaba', name: 'druid', version: '1.0.29'
compile('mysql:mysql-connector-java:5.1.31')
- 在
application.yml
中添加数据库相关配置。我们这里使用mysql数据库,阿里druid连接池,完整配置文件如下:
server:
port: 8880
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3306/microservice?useUnicode=true&characterEncoding=utf-8&useSSL=true
username : root
password : xda265856
driverClassName : com.mysql.jdbc.Driver
jpa:
hibernate:
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
ddl-auto: update
show-sql: true
编写代码
- 创建如下图所示的包及对应文件:
- Student.java
import javax.persistence.*;
@Entity
@Table(name = "tb_student")
public class Student {
//设置主键并且设置主键为自增
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
@Column(name = "student_id")
private long studentId;
@Column(name = "student_name")
private String studentName;
@Column(name = "student_age")
private int age;
@Column(name = "student_gender")
private int gender;
//省略 :getter and setter
.....
}
@Table注解可以指定该实体类对应的表名称
@Column注解指定该属性对应表中的字段
- StudentRepository.java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.virtue.pojo.Student;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
- StudentController.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.virtue.dao.StudentRepository;
import org.virtue.pojo.Student;
import java.util.List;
@Controller
public class StudentController {
@Autowired
private StudentRepository studentRepository;
@ResponseBody
@RequestMapping(value = "/students", method = {RequestMethod.GET})
public List<Student> showStudents(){
List<Student> students = studentRepository.findAll();
return students;
}
}
- 往数据库里添加几条测试数据
- 启动项目
- 通过postman访问后台接口,请求和接口如下图所示:
- 这里我们以CRUD为例,测试所有的流程
- 增加,通过post请求往后台发送数据,后台接口如下:
//@RequestBody注解对应请求body中的数据 @ResponseBody @RequestMapping(value = "/students", method = {RequestMethod.POST}) public String addStudent(@RequestBody Student student){ studentRepository.save(student); return "OK"; }
- 使用postman发送请求如下:
- 使用postman发送请求如下:
- 删除,通过delete请求往后台发送数据,后台接口如下:
@ResponseBody
@RequestMapping(value = "/students/{studentId}", method = {RequestMethod.DELETE})
public String deleteStudent(@PathVariable long studentId){
studentRepository.deleteById(studentId);
return "OK";
}
-
通过postman测试如下图所示:
-
修改,通过put请求往后台发送数据,后台接口如下:
@ResponseBody
@RequestMapping(value = "/students", method = {RequestMethod.PUT})
public String updateStudent(@RequestBody Student student){
studentRepository.save(student);
return "OK";
}
- 通过postman测试如下图所示:
响应优化
这里我们测试测试的时候,每次的响应值都是ok,这样很不友好,这里我们封装一个响应对象,来作为响应的载体。并定义一下项目的自定义异常,定义如下:
import org.virtue.basic.exception.BasicException;
public class BizResult<T> {
private String message;
private long retCode;
private T data;
private BizResult(T data) {
this.retCode = 0;
this.message = "成功";
this.data = data;
}
public BizResult() {
}
private BizResult(BasicException cm) {
if(cm == null){
return;
}
this.retCode = cm.getErrorCode().getCode();
this.message = cm.getMessage();
}
/**
* 成功时候的调用
* @return
*/
public static <T> BizResult<T> success(T data){
return new BizResult<T>(data);
}
/**
* 成功,不需要传入参数
* @return
*/
@SuppressWarnings("unchecked")
public static <T> BizResult<T> success(){
return (BizResult<T>) success("");
}
/**
* 失败时候的调用
* @return
*/
public static <T> BizResult<T> error(BasicException cm){
return new BizResult<T>(cm);
}
/**
* 失败时候的调用,扩展消息参数
* @param cm
* @param msg
* @return
*/
public static <T> BizResult<T> error(BasicException cm, String msg){
cm.getErrorCode().appendMsgToNew(cm.getMessage()+"--"+msg);
return new BizResult<T>(cm);
}
public T getData() {
return data;
}
public String getMessage() {
return message;
}
public long getRetCode() {
return retCode;
}
public void setMessage(String message) {
this.message = message;
}
public void setRetCode(long retCode) {
this.retCode = retCode;
}
public void setData(T data) {
this.data = data;
}
}
这时我们对修改
这个接口updateStudent
来进行响应的封装,如下所示:
@ResponseBody
@RequestMapping(value = "/students", method = {RequestMethod.PUT})
public BizResult updateStudent(@RequestBody Student student){
studentRepository.save(student);
BizResult bizResult = BizResult.success();
bizResult.setData("更新成功");
bizResult.setMessage("测试");
return bizResult;
}
获取的响应如下:
至此集成Spring Data JPA结束!
项目代码
- github:点击这里