Spring Data JPA 之 JpaRepository

JpaRepository是Spring提供的非常强大的基本接口。

1 JpaRepository

1.1 JpaRepository接口定义

JpaRepository接口的官方定义如下:

public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>

可以看出JpaRepository继承了接口PagingAndSortingRepository和QueryByExampleExecutor。而,PagingAndSortingRepository又继承CrudRepository。
因此,JpaRepository接口同时拥有了基本CRUD功能以及分页功能。

当我们需要定义自己的Repository的时候,我们可以继承JpaRepository,从而获得Spring为我们预先定义的多种基本数据操作方法。

public interface UserRepository extends JpaRepository<User, Integer> {

}

1.2 各函数说明

1.2.1 CrudRepository提供的函数

    /**
     * 保存一个实体。
     */
     S save(S entity);

    /**
     * 保存提供的所有实体。
     */
     Iterable saveAll(Iterable entities);

    /**
     * 根据id查询对应的实体。
     */
    Optional findById(ID id);

    /**
     * 根据id查询对应的实体是否存在。
     */
    boolean existsById(ID id);

    /**
     * 查询所有的实体。
     */
    Iterable findAll();

    /**
     * 根据给定的id集合查询所有对应的实体,返回实体集合。
     */
    Iterable findAllById(Iterable ids);

    /**
     * 统计现存实体的个数。
     */
    long count();

    /**
     * 根据id删除对应的实体。
     */
    void deleteById(ID id);

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

    /**
     * 删除给定的实体集合。
     */
    void deleteAll(Iterable entities);

    /**
     * 删除所有的实体。
     */
    void deleteAll();

1.2.2 PagingAndSortingRepository提供的函数

    /**
     * 返回所有的实体,根据Sort参数提供的规则排序。
     */
    Iterable findAll(Sort sort);

    /**
     * 返回一页实体,根据Pageable参数提供的规则进行过滤。
     */
    Page findAll(Pageable pageable);

1.2.3 JpaRepository提供的函数

    /**
     * 将所有未决的更改刷新到数据库。
     */
    void flush();

    /**
     * 保存一个实体并立即将更改刷新到数据库。
     */
     S saveAndFlush(S entity);

    /**
     * 在一个批次中删除给定的实体集合,这意味着将产生一条单独的Query。
     */
    void deleteInBatch(Iterable entities);

    /**
     * 在一个批次中删除所有的实体。
     */
    void deleteAllInBatch();

    /**
     * 根据给定的id标识符,返回对应实体的引用。
     */
    T getOne(ID id);

JpaRepository还继承了一个QueryByExampleExecutor,提供按“实例”查询,这里不做更多的研究。

2 函数测试

下面对以上Spring提供的所有函数进行测试,给出各函数的用法。

首先定义实体类Customer:

package com.tao.springboot.hibernate.entity;

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Table(name = "tb_customer")
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @NonNull private String name;
    @NonNull private Integer age;
}

然后定义接口CustomerRepository:

package com.tao.springboot.hibernate.repository;

import com.tao.springboot.hibernate.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;

public interface CustomerRepository extends JpaRepository {

}

接下来对各个方法进行测试~~~

2.1 save

    /**
     * 保存一个实体。
     */
    extends T> S save(S entity);

测试代码:

    @GetMapping("/customer/save")
    public Customer crudRepository_save() {

        // 保存一个用户michael
        Customer michael = new Customer("Michael", 26);
        Customer res = customerRepository.save(michael);
        return res;
    }

测试结果:
这里写图片描述
这里写图片描述

2.2 saveAll

    /**
     * 保存提供的所有实体。
     */
    extends T> Iterable saveAll(Iterable entities);

测试代码:

    @GetMapping("/customer/saveAll")
    public List crudRepository_saveAll() {

        // 保存指定集合的实体
        List customerList = new ArrayList<>();
        customerList.add(new Customer("Tom", 21));
        customerList.add(new Customer("Jack", 21));
        List res = customerRepository.saveAll(customerList);
        return res;
    }

测试结果:
Spring Data JPA 之 JpaRepository_第1张图片
这里写图片描述

2.3 findById

    /**
     * 根据id查询对应的实体。
     */
    Optional findById(ID id);

测试代码:

    @GetMapping("/customer/findById")
    public Customer crudRepository_findById() {

        // 根据id查询对应实体
        Optional customer = customerRepository.findById(1L);
        if(customer.isPresent()) {
            return customer.get();
        }
        return null;
    }

测试结果:
这里写图片描述

2.4 existsById

    /**
     * 根据id查询对应的实体是否存在。
     */
    boolean existsById(ID id);

测试代码:

    @GetMapping("/customer/existsById")
    public boolean crudRepository_existsById() {

        // 根据id查询对应的实体是否存在
        return customerRepository.existsById(1L);
    }

测试结果:
这里写图片描述

2.5 findAll

    /**
     * 查询所有的实体。
     */
    Iterable findAll();

测试代码:

    @GetMapping("/customer/findAll")
    public List crudRepository_findAll() {

        // 查询所有的实体
        List customerList = customerRepository.findAll();
        return customerList;
    }

测试结果:
这里写图片描述

2.6 findAllById

    /**
     * 根据给定的id集合查询所有对应的实体,返回实体集合。
     */
    Iterable findAllById(Iterable ids);

测试代码:

    @GetMapping("/customer/findAllById")
    public List crudRepository_findAllById() {

        // 根据给定的id集合查询所有对应的实体,返回实体集合
        List ids = new ArrayList<>();
        ids.add(2L);
        ids.add(1L);
        List customerList = customerRepository.findAllById(ids);
        return customerList;
    }

测试结果:
这里写图片描述

2.7 count

    /**
     * 统计现存实体的个数。
     */
    long count();

测试代码:

    @GetMapping("/customer/count")
    public Long crudRepository_count() {

        // 统计现存实体的个数
        return customerRepository.count();
    }

测试结果:
这里写图片描述

2.8 deleteById

    /**
     * 根据id删除对应的实体。
     */
    void deleteById(ID id);

测试代码:

    @GetMapping("/customer/deleteById")
    public void crudRepository_deleteById() {

        // 根据id删除对应的实体
         customerRepository.deleteById(1L);
    }

测试结果:
删除前~~
Spring Data JPA 之 JpaRepository_第2张图片
删除后~~
这里写图片描述
这里写图片描述

2.9 delete(T entity)

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

测试代码:

    @GetMapping("/customer/delete")
    public void crudRepository_delete() {

        // 删除给定的实体
        Customer customer = new Customer(2L, "Tom", 21);
        customerRepository.delete(customer);
    }

测试结果:
删除前~~
这里写图片描述
删除后~~
这里写图片描述
这里写图片描述

2.10 deleteAll(Iterable entities)

    /**
     * 删除给定的实体集合。
     */
    void deleteAll(Iterable entities);

测试代码:

    @GetMapping("/customer/deleteAll(entities)")
    public void crudRepository_deleteAll_entities() {

        // 删除给定的实体集合
        Customer tom = new Customer(2L,"Tom", 21);
        Customer jack = new Customer(3L,"Jack", 21);
        List entities = new ArrayList<>();
        entities.add(tom);
        entities.add(jack);
        customerRepository.deleteAll(entities);
    }

测试结果:
删除前~~
Spring Data JPA 之 JpaRepository_第3张图片
删除后~~
这里写图片描述
这里写图片描述

2.11 deleteAll

    /**
     * 删除所有的实体。
     */
    void deleteAll();

测试代码:

    @GetMapping("/customer/deleteAll")
    public void crudRepository_deleteAll() {

        // 删除所有的实体
        customerRepository.deleteAll();
    }

测试结果:
删除前~~
Spring Data JPA 之 JpaRepository_第4张图片
删除后~~
这里写图片描述
这里写图片描述

2.12 findAll(Sort sort)

    /**
     * 返回所有的实体,根据Sort参数提供的规则排序。
     */
    Iterable findAll(Sort sort);

测试代码:

    @GetMapping("/customer/findAll(sort)")
    public List pagingAndSortingRepository_findAll_sort() {

        // 返回所有的实体,根据Sort参数提供的规则排序
        // 按age值降序排序
        Sort sort = new Sort(Sort.Direction.DESC, "age");
        List res = customerRepository.findAll(sort);
        return res;
    }

测试结果:
Spring Data JPA 之 JpaRepository_第5张图片
格式化之后发现,确实是按照age的值降序输出的!!!

2.13 findAll(Pageable pageable)

    /**
     * 返回一页实体,根据Pageable参数提供的规则进行过滤。
     */
    Page findAll(Pageable pageable);

测试代码:

    @GetMapping("/customer/findAll(pageable)")
    public void pagingAndSortingRepository_findAll_pageable() {

        // 分页查询
        // PageRequest.of 的第一个参数表示第几页(注意:第一页从序号0开始),第二个参数表示每页的大小
        Pageable pageable = PageRequest.of(1, 5); //查第二页
        Page page = customerRepository.findAll(pageable);

        System.out.println("查询总页数:" + page.getTotalPages());
        System.out.println("查询总记录数:" + page.getTotalElements());
        System.out.println("查询当前第几页:" + (page.getNumber() + 1));
        System.out.println("查询当前页面的集合:" + page.getContent());
        System.out.println("查询当前页面的记录数:" + page.getNumberOfElements());
    }

测试结果:
这里写图片描述

你可能感兴趣的:(SpringBoot,数据库)