Spring Data JPA 之 JpaRepository的使用

目录
  • 1JpaRepository
    • 1.1JpaRepository接口定义
    • 1.2内置方法
      • 1.2.1CrudRepository<T,ID>提供的方法
      • 1.2.2PagingAndSortingRepository<T,ID>提供的方法
      • 1.2.3JpaRepository<T,ID>提供的方法
  • 2方法测试
    • 2.1save
    • 2.2saveAll
    • 2.3findById
    • 2.4existsById
    • 2.5findAll
    • 2.6findAllById
    • 2.7count
    • 2.8deleteById
    • 2.9delete(Tentity)
    • 2.10deleteAll(Iterable<?extendsT>entities)
    • 2.11deleteAll
    • 2.12findAll(Sortsort)
    • 2.13findAll(Pageablepageable)
  • 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());
    }

测试结果:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • Spring Data Jpa实现自定义repository转DTO

    近期项目中需要 关联 几张表再把字段转出来,在这里记录以下,我感觉网上写的都不太规范和清晰. @Entity @SqlResultSetMapping( name="TestMapping", entities = { @EntityResult( entityClass = com.xxx.xx.data.model.TestEntity.class, fields = { @FieldResult(name="id",column="id")

  • spring data jpa如何使用自定义repository实现类

    目录 spring data jpa使用自定义repository实现类 创建MyJpaRepository实现类 创建MyJpaRepositoryFactoryBean 配置JPA JPA自定义 Repository 方法 包结构 类与接口之间的关系代码 经过实践发现 spring data jpa使用自定义repository实现类 spring data jpa中使用JpaRepository等接口定义repository时,将默认使用SimpleJpaRepository 可通过自定义

  • SpringDataJpa:JpaRepository增删改查操作

    Jpa查询 1. JpaRepository简单查询 基本查询也分为两种,一种是spring data默认已经实现,一种是根据查询的方法来自动解析成SQL. 预先生成方法 spring data jpa 默认预先生成了一些基本的CURD的方法,例如:增.删.改等等 继承JpaRepository public interface UserRepository extends JpaRepository<User, Long> { } 使用默认方法 @Test public void testB

  • spring-data-jpa使用自定义repository来实现原生sql

    目录 使用自定义repository实现原生sql 自定义Repository接口 创建自定义RepositoryFactoryBean SpringDataJpa原生SQL查询 a.首先在StudentRepository里添加如下方法 b.在StudentController里面进行调用以上方法 使用自定义repository实现原生sql Spring Data JPA中的Repository是接口,是JPA根据方法名帮我们自动生成的.但很多时候,我们需要为Repository提供一些自定

  • Spring Data JPA 之 JpaRepository的使用

    目录 1JpaRepository 1.1JpaRepository接口定义 1.2内置方法 1.2.1CrudRepository<T,ID>提供的方法 1.2.2PagingAndSortingRepository<T,ID>提供的方法 1.2.3JpaRepository<T,ID>提供的方法 2方法测试 2.1save 2.2saveAll 2.3findById 2.4existsById 2.5findAll 2.6findAllById 2.7count

  • spring Data jpa简介_动力节点Java学院整理

    前言 自 JPA 伴随 Java EE 5 发布以来,受到了各大厂商及开源社区的追捧,各种商用的和开源的 JPA 框架如雨后春笋般出现,为开发者提供了丰富的选择.它一改之前 EJB 2.x 中实体 Bean 笨重且难以使用的形象,充分吸收了在开源社区已经相对成熟的 ORM 思想.另外,它并不依赖于 EJB 容器,可以作为一个独立的持久层技术而存在.目前比较成熟的 JPA 框架主要包括 Jboss 的 Hibernate EntityManager.Oracle 捐献给 Eclipse 社区的 E

  • spring data jpa分页查询示例代码

    最近项目上用就hibernate+spring data jpa,一开始感觉还不错,但是随着对业务的复杂,要求处理一些复杂的sql,就顺便研究了下,把结果记录下,以便日后查看.用到Specification,需要继承JpaSpecificationExecutor接口.(下面代码有的分页从0开始作为第一页,有的从1开始作为作为第一页,我也忘记,请自己测试) DAO层: import java.util.List; import org.springframework.data.domain.Pa

  • Spring Data JPA中的动态查询实例

    spring Data JPA大大的简化了我们持久层的开发,但是实际应用中,我们还是需要动态查询的. 比如,前端有多个条件,这些条件很多都是可选的,那么后端的SQL,就应该是可以定制的,在使用hibernate的时候,可以通过判断条件来拼接SQL(HQL),当然,Spring Data JPA在简化我们开发的同时,也是提供了支持的. 通过实现Criteria二实现的动态查询,需要我们的Repo接口继承JpaSpecificationExecutor接口,这是个泛型接口. 然后查询的时候,传入动态

  • Spring Data JPA实现动态条件与范围查询实例代码

    Spring Data JPA为我们提供了Query With Example来实现动态条件查询,当查询条件为空的时候,我们不用做大量的条件判断.但是Query With Example却不支持范围查询(包括日期范围,数值范围查询),本文通过Specification实现了既支持动态条件查询又支持范围查询的方法. 1 实现方式 1.1 范围对象Range定义 import java.io.Serializable; public class Range<E> implements Serial

  • spring data jpa使用详解(推荐)

    使用Spring data JPA开发已经有一段时间了,这期间学习了一些东西,也遇到了一些问题,在这里和大家分享一下. 前言: Spring data简介: Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map-reduce框架和云计算数据服务. Spring Data 包含多个子项目: Commons - 提供共享的基础框架,适合各个子项目使用,支持跨数据库持久化 JPA - 简化创建 JPA 数据访问层和跨存储的持久层

  • Spring Data JPA例子代码[基于Spring Boot、Mysql]

    关于Spring Data Spring社区的一个顶级工程,主要用于简化数据(关系型&非关系型)访问,如果我们使用Spring Data来开发程序的话,那么可以省去很多低级别的数据访问操作,如编写数据查询语句.DAO类等,我们仅需要编写一些抽象接口并定义相关操作即可,Spring会在运行期间的时候创建代理实例来实现我们接口中定义的操作. 关于Spring Data子项目 Spring Data拥有很多子项目,除了Spring Data Jpa外,还有如下子项目. Spring Data Comm

  • Spring Data Jpa+SpringMVC+Jquery.pagination.js实现分页示例

    本博客介绍基于Spring Data这款orm框架加上 Jquery.pagination插件实现的分页功能. 本博客是基于一款正在开发中的github开源项目的,项目代码地址:https://github.com/u014427391/jeeplatform 欢迎star(收藏)或者可以下载去学习,还在开发- 介绍一下Spring Data框架 spring Data : Spring 的一个子项目.用于简化数据库访问,支持NoSQL 和 关系数据存储. 下面给出SpringData 项目所支

  • Spring Data JPA 建立表的联合主键

    最近遇到了一个小的问题,就是怎么使用 Spring Data JPA 建立表的联合主键?然后探索出了下面的两种方式. 第一种方式: 第一种方式是直接在类属性上面的两个字段都加上 @Id 注解,就像下面这样,给 stuNo 和 stuName 这两个字段加上联合主键: @Entity @Table(name = "student") public class Student { @Id @Column(name = "stu_no", nullable = false

  • Spring Boot整合Spring Data JPA过程解析

    Spring Boot整合Spring Data JPA 1)加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> &l

随机推荐