1. 程式人生 > >Spring Data JPA 之 JpaRepository

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<T, ID>提供的函式

    /**
     * 儲存一個實體。
     */
    <S extends T> S save(S entity);

    /**
     * 儲存提供的所有實體。
     */
<S extends T> Iterable<S> saveAll(Iterable<S> entities); /** * 根據id查詢對應的實體。 */ Optional<T> findById(ID id); /** * 根據id查詢對應的實體是否存在。 */ boolean existsById(ID id); /** * 查詢所有的實體。 */ Iterable<T> findAll(); /** * 根據給定的id集合查詢所有對應的實體,返回實體集合。 */
Iterable<T> findAllById(Iterable<ID> ids); /** * 統計現存實體的個數。 */ long count(); /** * 根據id刪除對應的實體。 */ void deleteById(ID id); /** * 刪除給定的實體。 */ void delete(T entity); /** * 刪除給定的實體集合。 */ void deleteAll(Iterable<? extends T> entities); /** * 刪除所有的實體。 */ void deleteAll();

1.2.2 PagingAndSortingRepository<T, ID>提供的函式

    /**
     * 返回所有的實體,根據Sort引數提供的規則排序。
     */
    Iterable<T> findAll(Sort sort);

    /**
     * 返回一頁實體,根據Pageable引數提供的規則進行過濾。
     */
    Page<T> findAll(Pageable pageable);

1.2.3 JpaRepository<T, ID>提供的函式

    /**
     * 將所有未決的更改重新整理到資料庫。
     */
    void flush();

    /**
     * 儲存一個實體並立即將更改重新整理到資料庫。
     */
    <S extends T> S saveAndFlush(S entity);

    /**
     * 在一個批次中刪除給定的實體集合,這意味著將產生一條單獨的Query。
     */
    void deleteInBatch(Iterable<T> entities);

    /**
     * 在一個批次中刪除所有的實體。
     */
    void deleteAllInBatch();

    /**
     * 根據給定的id識別符號,返回對應實體的引用。
     */
    T getOne(ID id);

JpaRepository<T, ID>還繼承了一個QueryByExampleExecutor<T>,提供按“例項”查詢,這裡不做更多的研究。

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<Customer, Long> {

}

接下來對各個方法進行測試~~~

2.1 save

    /**
     * 儲存一個實體。
     */
    <S 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

    /**
     * 儲存提供的所有實體。
     */
    <S extends T> Iterable<S> saveAll(Iterable<S> entities);

測試程式碼:

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

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

測試結果:
這裡寫圖片描述
這裡寫圖片描述

2.3 findById

    /**
     * 根據id查詢對應的實體。
     */
    Optional<T> findById(ID id);

測試程式碼:

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

        // 根據id查詢對應實體
        Optional<Customer> 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<T> findAll();

測試程式碼:

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

        // 查詢所有的實體
        List<Customer> customerList = customerRepository.findAll();
        return customerList;
    }

測試結果:
這裡寫圖片描述

2.6 findAllById

    /**
     * 根據給定的id集合查詢所有對應的實體,返回實體集合。
     */
    Iterable<T> findAllById(Iterable<ID> ids);

測試程式碼:

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

        // 根據給定的id集合查詢所有對應的實體,返回實體集合
        List<Long> ids = new ArrayList<>();
        ids.add(2L);
        ids.add(1L);
        List<Customer> 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);
    }

測試結果:
刪除前~~
這裡寫圖片描述
刪除後~~
這裡寫圖片描述
這裡寫圖片描述

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<? extends T> entities)

    /**
     * 刪除給定的實體集合。
     */
    void deleteAll(Iterable<? extends T> 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<Customer> entities = new ArrayList<>();
        entities.add(tom);
        entities.add(jack);
        customerRepository.deleteAll(entities);
    }

測試結果:
刪除前~~
這裡寫圖片描述
刪除後~~
這裡寫圖片描述
這裡寫圖片描述

2.11 deleteAll

    /**
     * 刪除所有的實體。
     */
    void deleteAll();

測試程式碼:

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

        // 刪除所有的實體
        customerRepository.deleteAll();
    }

測試結果:
刪除前~~
這裡寫圖片描述
刪除後~~
這裡寫圖片描述
這裡寫圖片描述

2.12 findAll(Sort sort)

    /**
     * 返回所有的實體,根據Sort引數提供的規則排序。
     */
    Iterable<T> findAll(Sort sort);

測試程式碼:

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

        // 返回所有的實體,根據Sort引數提供的規則排序
        // 按age值降序排序
        Sort sort = new Sort(Sort.Direction.DESC, "age");
        List<Customer> res = customerRepository.findAll(sort);
        return res;
    }

測試結果:
這裡寫圖片描述
格式化之後發現,確實是按照age的值降序輸出的!!!

2.13 findAll(Pageable pageable)

    /**
     * 返回一頁實體,根據Pageable引數提供的規則進行過濾。
     */
    Page<T> findAll(Pageable pageable);

測試程式碼:

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

        // 分頁查詢
        // PageRequest.of 的第一個引數表示第幾頁(注意:第一頁從序號0開始),第二個引數表示每頁的大小
        Pageable pageable = PageRequest.of(1, 5); //查第二頁
        Page<Customer> 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());
    }

測試結果:
這裡寫圖片描述