美文网首页程序员
JPA 基础(1)—— 数据库持久化代码实战

JPA 基础(1)—— 数据库持久化代码实战

作者: 黄宝玲_1003 | 来源:发表于2019-03-26 14:45 被阅读0次

JPA 基础(1)—— 数据库持久化代码实战
JPA 基础(2)—— 分页操作
JPA 基础(3)—— Auditing
JPA 基础(4)—— 关联表映射

Spring Data JPA

什么是JPA(Java Persistent API)

  • jpa 是规范
  • hibernate实现了这个规范
  • spring data jpa对hibernate进行了封装

核心概念

  • Repository

Spring Data存储库抽象中的中央接口。它将表映射的实体类以及类的主键类型作为类型参数进行管理。

  • CrudRepository

继承Repository,对被管理的实体类提供复杂的CRUD(Create、Read、Update、Delete)功能。

  • PagingAndSortingRepository

继承CrudRepository,简化对实体的分页访问。

  • JpaRepository

继承PagingAndSortingRepository,一个特定的抽象。

接口

Repository

public interface Repository<T, ID> {
}

CrudRepository

public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {

    <S extends T> S save(S entity);       // 保存给定的实体

    Optional<T> findById(ID primaryKey);  // 返回由给定ID标识的实体

    Iterable<T> findAll();                // 返回所有实体        

    long count();                         // 返回实体数量     

    void delete(T entity);                // 删除给定的实体  

    boolean existsById(ID primaryKey);    // 指示是否存在具有给定ID的实体

    // … more functionality omitted.
}

PagingAndSortingRepository

public interface PagingAndSortingRepository<T, ID> extends CrudRepository<T, ID> {
    Iterable<T> findAll(Sort var1);  // 返回排序的实体列表

    Page<T> findAll(Pageable var1);  // 返回分页的实体
}

JpaRepository

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
    List<T> findAll();

    List<T> findAll(Sort var1);

    List<T> findAllById(Iterable<ID> var1);

    <S extends T> List<S> saveAll(Iterable<S> var1);

    void flush();

    <S extends T> S saveAndFlush(S var1);

    void deleteInBatch(Iterable<T> var1);

    void deleteAllInBatch();

    T getOne(ID var1);

    <S extends T> List<S> findAll(Example<S> var1);

    <S extends T> List<S> findAll(Example<S> var1, Sort var2);
}

代码实战

依赖包

<dependencies>
  <dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
  </dependency>
<dependencies>

配置文件

spring:
  jpa:
    database-platform: "org.hibernate.dialect.MySQL5InnoDBDialect"
    show-sql: "false"
  datasource:
    driver-class-name: "com.mysql.cj.jdbc.Driver"
    url: "jdbc:mysql://192.168.8.110:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false"
    username: "root"
    password: "root"

启动mysql容器

// 拉取mysql最新镜像
> docker pull mysql
// 运行容器
> docker run --name mysql -v /Users/hbl/data/mysql/data:/mysql_data -p 3306:3306 -e MYSQL_ROOT_PASSWORD=root -d mysql

创建一个test database 和 student table。

CREATE TABLE `student` (
  `no` char(36) NOT NULL,            // 学号
  `class_no` char(36) DEFAULT NULL,  // 班级号
  `grade` int(11) DEFAULT NULL,      // 成绩
  PRIMARY KEY (`no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

代码持久化

新建一个学生实体

@Data                     // 提供类所有属性的getter和setter方法,以及toString等方法
@Entity                   // 声明类为实体或表
@Table(name = "student")  // 声明表名
public class StudentEntity {
    @Id  // 声明该属性映射为数据库的主键列 
    // 自增主键用 @GeneratedValue(strategy=GenerationType.IDENTITY)
    private String no;

    @Column(name = "class_no")  // 持久化属性映射到数据库表,表中列明为class_no,Java是驼峰命名
    private String classNo;

    private Integer grade;
}

创建仓库方法

package com.jpa.test;

import org.springframework.data.jpa.repository.JpaRepository;
//import org.springframework.data.repository.CrudRepository;
//import org.springframework.data.repository.Repository;

// StudentRepository可以继承JpaRepository,JpaRepository相对于CrudRepository又封装了更多方法。如果直接继承最原始的Repository,就需要以特定的命名规则进行方法命名,JPA是能解析识别的,我们不需要为该接口提供实现。
public interface StudentRepository extends JpaRepository<StudentEntity, String> {
}
//public interface StudentRepository extends Repository<StudentEntity, String> {
//    StudentEntity findByNo(String no);
//}

测试

package com.jpa.test;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(value = {SpringExtension.class})  // 扩展项,有了SpringExtension,就可以在测试类中执行依赖注入
@SpringBootTest  // 为springApplication创建上下文并支持SpringBoot特性
public class StudentService {
    @Autowired   // 自动注入StudentRepository
    private StudentRepository studentRepository;

    @Test  // 测试方法
    public void getInfo() {
        System.out.println(studentRepository.findByNo("1"));
    }
}

结果:

JPA注解

注解 解释
@Entity 声明类为实体或表。
@Table 声明表名。
@Basic 指定非约束明确的各个字段。
@Embedded 指定类或它的值是一个可嵌入的类的实例的实体的属性。
@Id 指定的类的属性,用于识别(一个表中的主键)。
@GeneratedValue 指定如何标识属性可以被初始化,例如自动、手动、或从序列表中获得的值。
@Transient 指定的属性,它是不持久的,即:该值永远不会存储在数据库中。
@Column 指定持久属性栏属性。
@SequenceGenerator 指定在@GeneratedValue注解中指定的属性的值。它创建了一个序列。
@TableGenerator 指定在@GeneratedValue批注指定属性的值发生器。它创造了的值生成的表。
@AccessType 这种类型的注释用于设置访问类型。如果设置@AccessType(FIELD),则可以直接访问变量并且不需要getter和setter,但必须为public。如果设置@AccessType(PROPERTY),通过getter和setter方法访问Entity的变量。
@JoinColumn 指定一个实体组织或实体的集合。这是用在多对一和一对多关联。
@UniqueConstraint 指定的字段和用于主要或辅助表的唯一约束。
@ColumnResult 参考使用select子句的SQL查询中的列名。
@ManyToMany 定义了连接表之间的多对多一对多的关系。
@ManyToOne 定义了连接表之间的多对一的关系。
@OneToMany 定义了连接表之间存在一个一对多的关系。
@OneToOne 定义了连接表之间有一个一对一的关系。
@NamedQueries 指定命名查询的列表。
@NamedQuery 指定使用静态名称的查询。

相关文章

网友评论

    本文标题:JPA 基础(1)—— 数据库持久化代码实战

    本文链接:https://www.haomeiwen.com/subject/ctycyqtx.html