Spring Data JPA Quick Guide
  • Spring Data JPA 快速指南
  • 配置依赖
  • 配置数据源
  • 数据库编码与词语定序
  • Core Concepts
  • 基本用法
  • Transactions
    • 什么是事务
    • 配置事务(@EnableTransactionManagement)
    • 配置事务(XML)
    • 配置事务(@Transactional)
    • @Transactional 实现细节
    • Transaction and Spring Data JPA
    • 事务隔离
    • 事务传播
  • Query Creation from Method Names
  • Using @Query
  • Sorting and Pagination
  • Projection
  • Specification
  • Query by Example
  • javax.persistence Annotations
    • @OneToOne (bidirectional)
      • Usage
      • PO Serialization
      • Save and Update
      • Nested Projection
      • @MapsId
    • @OneToMany (bidirectional)
    • @OneToMany (unidirectional)
    • @ManyToMany (bidirectional)
      • Many-to-Many Using a Composite Key
由 GitBook 提供支持
在本页

基本用法

Spring Data JPA 的基本使用方法

使用 Spring Data JPA,你需要定义两类东西:

  • Entity

  • Repository

定义实体:

package cn.com.iamddch.sia1;

import lombok.*;
import org.hibernate.Hibernate;

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

@Entity
@Getter
@Setter
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false)
    private Long id;
    private String name;
    private Integer age;
}

需要注意,@Entity @Id @GeneratedValue @Column 等注解必须都来自 javax.persistence。

使用 @Getter @Setter 来标记实体类,而不是 @Data。

Using @Data for JPA entities is not recommended. It can cause severe performance and memory consumption issues.

Student 类会被映射到数据库表 student,实例域也会被映射到与其名字相同的数据库表的列。注意,实例域之所以可以产生同名列映射,不是因为其实例域的名字,而是来自 getter 或 setter 方法。

定义 Repository:

package cn.com.iamddch.sia1;

import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentRepository extends JpaRepository<Student, Long> {}

你没看错,不需要额外操作,只需简单地新建一个 StudentRepository 接口,继承 JpaRepository,并且填入该 Repository 管理的实体类和实体的主键类型即可。

由于继承了 JpaRepository,参照上一节我们提到的派生关系,StudentRepository 会拥有许多预定义的方法,所以不必我们自己编写。

JpaRepository默认实现的常用方法有:

repo.findAll();
repo.save(object);
repo.delete(object);
repo.delete(id);
repo.findOne(id);
repo.deleteAll();
repo.existes(id);  // boolean

注意:编写 Spring Data JPA 的 Repository 不需要使用 @Repository 注解!

使用 Repository:

package cn.com.iamddch.sia1;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    // 注入 Repository
    private final StudentRepository studentRepository;

    @Autowired
    public StudentController(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @GetMapping("/all")
    public List<Student> getAllStudent() {
        return studentRepository.findAll();
    }

    @PostMapping("/add")
    public void addStudent(@RequestBody Student student) {
        if (student.getId() != null) {
            // client should not specify id
            student.setId(null);
        }
        studentRepository.save(student);
    }
}

使用 Spring Data JPA 简单且优雅,你不需要自己编写 .sql 文件来建表,因为 Spring Data JPA 会依照实体类自动生成;你也不需要自己编写 SQL 查询语句,因为 Spring Data JPA 已经预定义了很多基础操作,而自己添加一些查询也可以不需要编写 SQL 语句(之后你将看到)。不是每一个后端开发者都是 DBA (Database Administrator),而 Spring Data JPA 就是你最好的选择。

上一页Core Concepts下一页Transactions

最后更新于3年前