SpringBoot 整合Spring Data JPA

作者Gitee地址 https://gitee.com/thciweicloud
作者项目 面包博客,一个微服务架构的前后端分离博客系统。

SpringBoot 整合Spring Data JPA

JPA Hibernate 框架就是一个 JPA 的实现

Spring Data JPA不是对 JPA 规范的具体实现,本身是一个抽象层

  • 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>

    <groupId>com.thciwei</groupId>
    <artifactId>springbootJPA</artifactId>
    <version>1.0-SNAPSHOT</version>
<parent>
    <artifactId>spring-boot-parent</artifactId>
    <groupId>org.springframework.boot</groupId>
    <version>2.1.8.RELEASE</version>
</parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

</project>
  • 实体类Student
package com.thciwei.entity;

import lombok.Data;

import javax.persistence.*;
import java.util.Date;

@Data
@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column
    private String name;
    @Column
    private Double score;
    @Column
    private Date birthday;
}

@Entity 表示他是跟表映射的实体类

@Id是指定一个作为主键

@GeneratedValue 生成策略

(strategy = GenerationType.IDENTITY) 选择自增

@Column 其他字段都用 column 映射

  • 创建 studentRepository
package com.thciwei.repository;

import com.thciwei.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student,Long> {
//public Student getById(long id);   自定义findById方法,但是命名要符合规范

}

需要继承一个接口 JpaRepository,传一个泛型<>

JpaRepository<Student,Long> 当前实体类类型,主键字段对应类型

JPA并没有实现,仍然是一个抽象层,不需要写实现类Impl,真正的实现在是底层 hibernate 来实现

  • 创建Handler,注入 StudentRepository
package com.thciwei.controller;

import com.thciwei.entity.Student;
import com.thciwei.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentHandler {
    @Autowired
    private StudentRepository studentRepository;
    @GetMapping("/findAll")
    public List<Student> findAll(){
        return studentRepository.findAll();
    }
    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") long id){
       return studentRepository.findById(id).get();
    }
    @PostMapping("/save")
    public Student save(@RequestBody Student student){
        return studentRepository.save(student);
    }
    @PutMapping("/update")
    public Student update(@RequestBody Student student){
        return studentRepository.save(student);
    }
    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        studentRepository.deleteById(id);
    }

}

studentRepository.findById(id).get(); 这里直接使用 findById会报错因为,源码处返回值是一个类似集合的东西,那么我们调用 get方法就好了,或者我们在StudentRepository处自定义方法,如 getById ,但自定义方法要遵守一定的规范

public Student getById(long id);

  • application.yml
server:
  port: 8181
spring:
  datasource:
    url:  jdbc:mysql://localhost:3306/mbtest?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: thciwei
    driver-class-name: com.mysql.cj.jdbc.Driver
  jpa:
    show-sql: true
    properties:
      hibernate:
        format_sql: true
  • 启动类
package com.thciwei;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class,args);
    }
}

使用 postman 测试增删改查

上一篇:idea生成JPA实体类


下一篇:Spring Data JPA应用 之查询分析