Spring Data JPA 之 JpaRepository的使用
作者:西瓜游侠 发布时间:2023-11-24 21:23:40
SpringBoot版本:2.3.2.RELEASE
SpringBoot Data JPA版本:2.3.2.RELEASE
JpaRepository是SpringBoot Data JPA提供的非常强大的基础接口。
1 JpaRepository
1.1 JpaRepository接口定义
JpaRepository接口的官方定义如下:
@NoRepositoryBean
public interface JpaRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T>
可以看出JpaRepository继承了接口PagingAndSortingRepository和QueryByExampleExecutor。而PagingAndSortingRepository又继承CrudRepository。因此,JpaRepository接口同时拥有了基本CRUD功能以及分页功能。
当我们需要定义自己的Repository接口的时候,我们可以直接继承JpaRepository,从而获得SpringBoot Data JPA为我们内置的多种基本数据操作方法,例如:
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 方法测试
下面对以上提供的所有内置方法进行测试,给出各方法的用法。
首先定义实体类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)
@Column(nullable = false)
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
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());
}
测试结果:
来源:https://blog.csdn.net/hbtj_1216/article/details/79773839


猜你喜欢
- 一.NET Remoting 介绍简介.NET Remoting与MSMQ不同,它不支持离线可得,另外只适合.NET平台的程序进行通信。它提
- 前言在面对 生产者-消费者 的场景下, netcore 提供了一个新的命名空间 System.Threading.Channels 来帮助我
- 相关api见:点击进入/* * Copyright 2014 the original author or authors. * * Lic
- 最近做一个项目,因为涉及到注册,因此需要发送短信,一般发送短信都有一个倒计时的小按钮,因此,就做了一个,在此做个记录。一、发送消息没有调用公
- synchronized关键字顾名思义,是用于同步互斥的作用的。这里精简的记一下它的使用方法以及意义:1. 当synchronized修饰
- 使用简单的fragment实现左侧导航,供大家参考,具体内容如下先上效果图:MainActivity.javapublic class Ma
- 我最近上班又遇到一个小难题了,就是如题所述:ViewPager预加载的问题。相信用过ViewPager的人大抵都有遇到过这种情况,网上的解决
- 对于初学java的同学来说,第一件事不是写hello world,而是搭建好java开发环境,下载jdk,安装,配置环境变量。这些操作在xp
- <?xml version="1.0" encoding="UTF-8" ?> <
- Android Studio在实现隐藏标题栏和状态栏上和Eclipse是完全不一样的。在Eclipse上隐藏标题栏和状态栏的代码如下:方法一
- 本文实例为大家分享了Android实现图片点击放大的具体代码,供大家参考,具体内容如下在我的项目中,有点击图片banner后放大浏览的功能。
- 1. String对象不可改变的特性下图显示了如下代码运行的过程:String s = "abcd"; s = s.co
- 笔者发现在很多应用中,都有自动获取验证码的功能:点击获取验证码按钮,收到短信,当前应用不需要退出程序就可以获取到短信中的验证码,并自动填充。
- // Create a handler for a click event.button1.Click += delegate(System
- 本课程的目标是帮你更有效的使用Java。其中讨论了一些高级主题,包括对象的创建、并发、序列化、反射以及其他高级特性。本课程将为你的精通Jav
- MyBatis的注解实现复杂映射开发实现复杂关系映射之前我们可以在映射文件中通过配置来实现,使用注解开发后,我们可以使用@Results注解
- 命令行编译java文件import java.util.*;public class shuchu{ public
- 概述:App几乎都离不开与服务器的交互,本文主要讲解了flutter网络请求三种方式 flutter自带的HttpClient、 第三方库h
- 导语在使用flutter 自带图片组件的过程中,大家有没有考虑过flutter是如何加载一张网络图片的? 以及对自带的图片组件我们可以做些什
- 简介JSON Web Token(缩写 JWT)是目前最流行的跨域认证解决方案。JSON Web Token 入门教程 这篇文章可以帮你了解