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);

 

测试结果:

格式化之后发现,确实是按照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());
}

测试结果:

 

转载于:https://www.cnblogs.com/powerwu/articles/10709745.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值