Spring Boot JPA 本机查询示例

news2025/2/25 4:07:22

在本教程中,您将了解如何在 Spring 引导中使用 Spring Data JPA 本机查询示例(带参数)。我将向您展示:

  • 将 Spring JPA 本机查询与@Query注释一起使用的方法
  • 如何在 Spring 引导中执行 SQL 查询
  • 具有 WHERE 条件的 JPA 选择查询示例

相关文章:
–Spring JPA @Query Spring Boot 中的 JPQL 示例 – Spring Boot
中的 JPA 派生查询示例 – Spring Boot 中的 JPA 实体管理器示例–Spring Boot, Spring Data JPA – Rest CRUD API 示例–Spring Boot
分页和排序示例– 带有多部分文件的
Spring
启动文件上传示例

–Spring Boot Authentication with Spring Security & JWT
–Spring JPA + H2 example–Spring JPA + MySQL example–Spring JPA + PostgreSQL example–Spring JPA + Oracle example–Spring JPA + SQL Server example



– Spring JPA + SQL Server 示例

关联:
–JPA 在春季引导中使用休眠的一对一示例–使用休眠和春季引导的 JPA 一对多示例–JPA 多对多示例与春季引导

中的休眠示例

内容[隐藏]

  • JPQL 与本机查询
  • 带有 Spring 引导的 Spring JPA 本机查询示例
  • 创建和设置 Spring Boot 项目
  • 配置 Spring 数据源、JPA、Hibernate
  • 创建实体
  • 为 JPA 本机查询方法定义存储库
  • JPA 本机查询 选择位置条件示例
  • 大于或等于的 JPA 本机查询
  • JPA 本机查询之间
  • 带参数的 JPA 本机查询示例
  • JPA 本机查询顺序(按描述/ASC)
  • JPA 本机查询排序依据
  • JPA 本机查询分页
  • JPA 本机查询更新
  • 运行 Spring JPA 查询项目
  • 结论
  • 延伸阅读
  • 源代码

JPQL 与本机查询

Spring JPA 同时支持 JPQL 和 Native Query。

Jakarta Persistence Query Language(JPQL;以前称为Java Persistence Query Language)是一种独立于平台的面向对象的查询语言,定义为Jakarta Persistence(JPA;以前称为Java Persistence API)规范的一部分 - 维基百科

JPQL 的灵感来自 SQL,其查询在语法上类似于 SQL 查询,但针对存储在关系数据库中的 JPA 实体对象进行操作,而不是直接使用数据库表。

以下是使用 JPQL 和@Query注释的自定义查询示例:

@Query("SELECT t FROM Tutorial t")
List<Tutorial> findAll();

@Query("SELECT t FROM Tutorial t WHERE t.published=true")
List<Tutorial> findByPublished();

有关更多详细信息,请访问:
Spring JPA @Query Spring Boot 中使用 JPQL 的示例

JPQL 仅支持 SQL 标准的子集。如果要进行复杂的查询,请查看本机 SQL 查询。
这是如何在 Spring Boot 中使用@Query注释执行 SQL 本机查询的方法:

  • value属性中定义 SQL
  • nativeQuery属性值设置为true
@Query(value = "SELECT * FROM tutorials", nativeQuery = true)
List<Tutorial> findAllNative();

@Query(value = "SELECT * FROM tutorials t WHERE t.published=true", nativeQuery = true)
List<Tutorial> findByPublishedNative();

您需要注意:
– Spring Data JPA 不会将查询调整为数据库的特定 SQL 方言,因此请确保提供的语句受 RDBMS 支持。
– Spring Data JPA目前不支持本机查询的动态排序,因为它必须操作声明的实际查询,这对于本机SQL无法可靠地执行。

例如,我们不能在以下方法中使用动态排序:

// JPQL: ok
@Query("SELECT * FROM tutorials t WHERE t.title LIKE %?1%")
List<Tutorial> findByTitleAndSort(String title, Sort sort);

// Native query: throw InvalidJpaQueryMethodException
@Query(value = "SELECT * FROM tutorials t WHERE t.title LIKE %?1%", nativeQuery = true)
List<Tutorial> findByTitleAndSortNative(String title, Sort sort);

但是我们可以改用Pageable对象进行排序。

让我们看看我们如何在 Spring Boot 示例中进行 JPA 本机查询。

带有 Spring 引导的 Spring JPA 本机查询示例

–科技:

  • Java 8
  • Spring Boot 2.6.3 (with Spring Data JPA)
  • MySQL/PostgreSQL/H2 (embedded database)
  • Maven 3.8.1

– 项目结构:

 

让我简要解释一下。

  • Tutorial数据模型类对应于实体和表教程
  • TutorialRepository是一个扩展JpaRepository的接口,用于 CRUD 方法和自定义查找器方法(使用本机查询)。它将被SpringBootQueryExampleApplication自动连接。
  • SpringBootQueryExampleApplication是SpringBootApplication实现CommandLineRunner。我们将在TutorialRepository里运行查询方法。
  • application.properties中配置Spring Datasource,JPA和Hibernate。
  • pom.xml包含 Spring Boot 和 MySQL/PostgreSQL/H2 数据库的依赖项。

创建和设置 Spring Boot 项目

使用 Spring Web 工具或您的开发工具(Spring Tool Suite、Eclipse、Intellij)创建 Spring Boot 项目。

然后打开pom.xml并添加以下依赖项:

<!-- web for access H2 database UI -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

我们还需要再添加一个依赖项。
如果你想使用MySQL

<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<scope>runtime</scope>
</dependency>

– 或PostgreSQL

<dependency>
	<groupId>org.postgresql</groupId>
	<artifactId>postgresql</artifactId>
	<scope>runtime</scope>
</dependency>

– 或H2(嵌入式数据库):

<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>

配置 Spring 数据源、JPA、Hibernate

在 src/main/resources 文件夹下,打开 application.properties 并编写这些行。

– 对于 MySQL:

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update

对于PostgreSQL:

spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
spring.datasource.username= postgres
spring.datasource.password= 123

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
  • spring.datasource.username & spring.datasource.password属性与数据库安装相同。
  • Spring Boot 使用 Hibernate 进行 JPA 实现,我们配置 MySQL 或 PostgreSQLMySQL5InnoDBDialectPostgreSQLDialect
  • spring.jpa.hibernate.ddl-auto用于数据库初始化。我们将值设置为值,以便在数据库中自动创建一个与定义的数据模型对应的表。对模型的任何更改也将触发对表的更新。对于生产,此属性应该是。updatevalidate

– 对于 H2 数据库:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
 
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update

spring.h2.console.enabled=true
# default path: h2-console
spring.h2.console.path=/h2-ui
  • spring.datasource.url:用于内存数据库和基于磁盘的数据库。jdbc:h2:mem:[database-name]jdbc:h2:file:[path/database-name]
  • 我们为 H2 数据库配置配置H2Dialect
  • spring.h2.console.enabled=true告诉 Spring 启动 H2 数据库管理工具,您可以在浏览器上访问此工具:http://localhost:8080/h2-console
  • spring.h2.console.path=/h2-ui用于 H2 控制台的 URL,因此默认 url 将更改为。http://localhost:8080/h2-consolehttp://localhost:8080/h2-ui

创建实体

model 包中,我们定义类Tutorial

教程具有以下字段:id, title, level, description, published, createdAt

model/Tutorial.java

package com.bezkoder.spring.jpa.query.model;

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "tutorials")
public class Tutorial {

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

  private String title;

  private String description;
  
  private int level;

  private boolean published;
  
  @Temporal(TemporalType.TIMESTAMP)
  private Date createdAt;

  public Tutorial() {

  }

  public Tutorial(String title, String description, int level, boolean published, Date createdAt) {
    this.title = title;
    this.description = description;
    this.level = level;
    this.published = published;
    this.createdAt = createdAt;
  }

  // getters and setters
}

@Entity注释表示该类是持久性 Java 类。

@Table注释提供映射此实体的表。

@Id注释用于主键。
–​​​​​​​@GeneratedValue注释用于定义主键的生成策略。

@Temporal注释在时间戳和或java.util.Date之间来回转换到时间。例如,​​​​​​​​​​​​​​@Temporal(TemporalType.DATE)删除时间值并仅保留日期。

@Temporal(TemporalType.DATE)
private Date createdAt;

为 JPA 本机查询方法定义存储库

让我们创建一个存储库来与数据库进行交互。
repository 包中,创建TutorialRepository扩展​​​​​​​JpaRepository接口。

repository/TutorialRepository.java

package com.bezkoder.spring.jpa.query.repository;

import com.bezkoder.spring.jpa.query.model.Tutorial;

public interface TutorialRepository extends JpaRepository<Tutorial, Long> {

}

在此接口中,我们将编写 JPA 本机查询(带参数)以从数据库中获取数据。

假设我们已经有了这样的tutorials 表:

 

JPA 本机查询 选择位置条件示例

让我们使用@Query注释来创建带有 SELECT 和 WHERE 关键字的 Spring JPA 本机查询。

@Query(value = "SELECT * FROM tutorials", nativeQuery = true)
List<Tutorial> findAll();

@Query(value = "SELECT * FROM tutorials t WHERE t.published=?1", nativeQuery = true)
List<Tutorial> findByPublished(boolean isPublished);

@Query(value = "SELECT * FROM tutorials t WHERE t.title LIKE %?1%", nativeQuery = true)
List<Tutorial> findByTitleLike(String title);

@Query(value = "SELECT * FROM tutorials t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%'))", nativeQuery = true)
List<Tutorial> findByTitleLikeCaseInsensitive(String title);

结果:

List<Tutorial> tutorials = new ArrayList<>();

tutorials = tutorialRepository.findAll();
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=2, title=Java Spring, description=Tut#2 Description, level=1, published=false, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=4, title=Spring Boot, description=Tut#4 Description, level=2, published=false, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
*/

tutorials = tutorialRepository.findByPublished(true);
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

tutorials = tutorialRepository.findByTitleLike("ata");
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

tutorials = tutorialRepository.findByTitleLikeCaseInsensitive("dat");
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

大于或等于的 JPA 本机查询

Spring 数据 JPA 本机查询大于或等于日期/列:

@Query(value = "SELECT * FROM tutorials t WHERE t.level >= ?1", nativeQuery = true)
List<Tutorial> findByLevelGreaterThanEqual(int level);

@Query(value = "SELECT * FROM tutorials t WHERE t.created_at >= ?1", nativeQuery = true)
List<Tutorial> findByDateGreaterThanEqual(Date date);

结果:

tutorials = tutorialRepository.findByLevelGreaterThanEqual(3);
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
*/

Date myDate = new SimpleDateFormat("yyyy-MM-dd").parse("2022-05-11");

tutorials = tutorialRepository.findByDateGreaterThanEqual(myDate);
show(tutorials);
/*
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
*/

JPA 本机查询之间

春季数据 JPA 本机查询 日期/列之间:

@Query(value = "SELECT * FROM tutorials t WHERE t.level BETWEEN ?1 AND ?2", nativeQuery = true)
List<Tutorial> findByLevelBetween(int start, int end);

@Query(value = "SELECT * FROM tutorials t WHERE t.created_at BETWEEN ?1 AND ?2", nativeQuery = true)
List<Tutorial> findByDateBetween(Date start, Date end);

结果:

tutorials = tutorialRepository.findByLevelBetween(3, 5);
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
*/

Date myDate1 = new SimpleDateFormat("yyyy-MM-dd").parse("2022-04-11");
Date myDate2 = new SimpleDateFormat("yyyy-MM-dd").parse("2022-05-11");

tutorials = tutorialRepository.findByDateBetween(myDate1, myDate2);
show(tutorials);
/*
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=4, title=Spring Boot, description=Tut#4 Description, level=2, published=false, createdAt=2022-04-26 00:00:00.0]
*/

带参数的 JPA 本机查询示例

在上面的例子中,我们使用位置参数:参数由它们在查询中的位置引用(定义后跟一个数字(?1,?2,...)。弹簧数据JPA将自动替换同一位置的每个参数的值。?

绑定值的另一种方法是命名参数。命名参数以参数名称开头 (,, ...)。::title:date

例如:

@Query(value = "SELECT * FROM tutorials t WHERE t.published=:isPublished AND t.level BETWEEN :start AND :end", nativeQuery = true)
List<Tutorial> findByLevelBetween(@Param("start") int start, @Param("end") int end, @Param("isPublished") boolean isPublished);

结果:

tutorials = tutorialRepository.findByLevelBetween(3, 5, true);
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

JPA 本机查询顺序(按描述/ASC)

Spring 数据 JPA 本机查询顺序按列进行筛选的示例:

@Query(value = "SELECT * FROM tutorials t ORDER BY t.level DESC", nativeQuery = true)
List<Tutorial> findAllOrderByLevelDesc();

@Query(value = "SELECT * FROM tutorials t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%')) ORDER BY t.level ASC", nativeQuery = true)
List<Tutorial> findByTitleOrderByLevelAsc(String title);

@Query(value = "SELECT * FROM tutorials t WHERE t.published=true ORDER BY t.created_at DESC", nativeQuery = true)
List<Tutorial> findAllPublishedOrderByCreatedDesc();

结果:

tutorials = tutorialRepository.findAllOrderByLevelDesc();
show(tutorials);
/*
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=4, title=Spring Boot, description=Tut#4 Description, level=2, published=false, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=2, title=Java Spring, description=Tut#2 Description, level=1, published=false, createdAt=2022-03-11 00:00:00.0]
*/

tutorials = tutorialRepository.findByTitleOrderByLevelAsc("at");
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
*/

tutorials = tutorialRepository.findAllPublishedOrderByCreatedDesc();
show(tutorials);
/*
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
*/

JPA 本机查询排序依据

Spring Data JPA 目前不支持本机查询的动态排序,因为它必须操作声明的实际查询,这对于本机 SQL 无法可靠地执行此操作。但是,您可以通过自己指定计数查询来使用本机查询进行分页 - 官方 Spring 文档

/* InvalidJpaQueryMethodException
@Query(value = "SELECT * FROM tutorials t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%'))", nativeQuery = true)
List<Tutorial> findByTitleAndSort(String title, Sort sort);
*/

那么,如何处理动态排序呢?
我们可以改用Pageable对象。例如:

@Query(value = "SELECT * FROM tutorials t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%'))", nativeQuery = true)
Page<Tutorial> findByTitleLike(String title, Pageable pageable);

@Query(value = "SELECT * FROM tutorials t WHERE t.published=?1", nativeQuery = true)
Page<Tutorial> findByPublished(boolean isPublished, Pageable pageable);

结果:

Pageable pageable1 = PageRequest.of(0, 1000, Sort.by("level").descending());

tutorials = tutorialRepository.findByTitleLike("at", pageable1).getContent();
show(tutorials);
/*
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
*/

Pageable pageable2 = PageRequest.of(0, 1000, Sort.by("title").descending());

tutorials = tutorialRepository.findByTitleLike("at", pageable2).getContent();
show(tutorials);
/*
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
*/

Pageable pageable3 = PageRequest.of(0, 1000, Sort.by("level").descending());

tutorials = tutorialRepository.findByPublished(false, pageable3).getContent();
show(tutorials);
/*
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=4, title=Spring Boot, description=Tut#4 Description, level=2, published=false, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=2, title=Java Spring, description=Tut#2 Description, level=1, published=false, createdAt=2022-03-11 00:00:00.0]
*/

JPA 本机查询分页

Spring Data JPA 本机查询示例使用类进行分页(带有排序和过滤):Pageable

@Query(value = "SELECT * FROM tutorials", nativeQuery = true)
Page<Tutorial> findAllWithPagination(Pageable pageable);

结果:

int page = 0;
int size = 3;

Pageable pageable = PageRequest.of(page, size);

tutorials = tutorialRepository.findAllWithPagination(pageable).getContent();
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=2, title=Java Spring, description=Tut#2 Description, level=1, published=false, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
*/

pageable = PageRequest.of(page, size, Sort.by("level").descending());

tutorials = tutorialRepository.findAllWithPagination(pageable).getContent();
show(tutorials);
/*
Tutorial [id=7, title=Spring Security, description=Tut#7 Description, level=5, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=6, title=Spring Batch, description=Tut#6 Description, level=4, published=false, createdAt=2022-05-19 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

JPA 本机查询更新

Spring Data JPA 本机查询,用于更新实体,同时使用:@Query@Transactional@Modifying

@Transactional
@Modifying
@Query(value = "UPDATE tutorials SET published=true WHERE id=?1", nativeQuery = true)
int publishTutorial(Long id);

结果:

tutorialRepository.deleteAll();

Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse("2022-03-11");
Date date2 = new SimpleDateFormat("yyyy-MM-dd").parse("2022-04-26");
Date date3 = new SimpleDateFormat("yyyy-MM-dd").parse("2022-05-19");

tutorialRepository.save(new Tutorial("Spring Data", "Tut#1 Description", 3, false, date1));
tutorialRepository.save(new Tutorial("Java Spring", "Tut#2 Description", 1, false, date1));
tutorialRepository.save(new Tutorial("Hibernate", "Tut#3 Description", 3, false, date2));
tutorialRepository.save(new Tutorial("Spring Boot", "Tut#4 Description", 2, false, date2));
tutorialRepository.save(new Tutorial("Spring Data JPA", "Tut#5 Description", 3, false, date3));
tutorialRepository.save(new Tutorial("Spring Batch", "Tut#6 Description", 4, false, date3));
tutorialRepository.save(new Tutorial("Spring Security", "Tut#7 Description", 5, false, date3));

List<Tutorial> tutorials = new ArrayList<>();

tutorials = tutorialRepository.findAll();
show(tutorials); // published = false for all

tutorialRepository.publishTutorial(tutorials.get(0).getId());
tutorialRepository.publishTutorial(tutorials.get(2).getId());
tutorialRepository.publishTutorial(tutorials.get(4).getId());

tutorials = tutorialRepository.findByPublished(true);
show(tutorials);
/*
Tutorial [id=1, title=Spring Data, description=Tut#1 Description, level=3, published=true, createdAt=2022-03-11 00:00:00.0]
Tutorial [id=3, title=Hibernate, description=Tut#3 Description, level=3, published=true, createdAt=2022-04-26 00:00:00.0]
Tutorial [id=5, title=Spring Data JPA, description=Tut#5 Description, level=3, published=true, createdAt=2022-05-19 00:00:00.0]
*/

运行 Spring JPA 查询项目

让我们打开,我们将在这里实现和自动连线接口来运行 JPA 查询方法。SpringBootQueryExampleApplication.javaCommandLineRunnerTutorialRepository

package com.bezkoder.spring.jpa.query;

// import ...

@SpringBootApplication
public class SpringJpaNativeQueryExampleApplication implements CommandLineRunner {

  @Autowired
  TutorialRepository tutorialRepository;

  public static void main(String[] args) {
    SpringApplication.run(SpringJpaNativeQueryExampleApplication.class, args);
  }

  @Override
  public void run(String... args) throws Exception {
    // call tutorialRepository methods here
  }

  private void show(List<Tutorial> tutorials) {
    tutorials.forEach(System.out::println);
  }
}

结论

今天我们已经知道如何在Spring Boot示例中使用注释使用Spring JPA Native查询(带参数)。@Query

您可以使用以下方法继续编写 CRUD Rest API:
Spring Boot、Spring Data JPA – Rest CRUD API 示例

如果要为 JPA 存储库编写单元测试:
Spring 引导单元测试 带有 @DataJpaTest 的 JPA 存储库

您还可以通过本教程了解:
– 如何在 AWS 上部署此 Spring 启动应用程序(免费)。
– dockerize withDocker Compose: Spring Boot and MySQL 示例
– 通过这篇文章
上传 Excel 文件并将数据存储在 MySQL 数据库中的方法– 通过这篇文章上传 CSV 文件并将数据存储在 MySQL 中。

祝你学习愉快!再见。

延伸阅读

  • 具有 Spring 安全性和 JWT 身份验证的安全 Spring 启动应用程序
  • 春季数据 JPA 参考文档
  • Spring 引导分页和排序示例

全栈 CRUD 应用程序:
–Vue + 弹簧引导示例–角度 8 + 弹簧引导示例–角度 10 + 弹簧引导示例–角度 11 + 弹簧引导示例–角度 12 + 弹簧引导示例–角度 13 + 弹簧引导示例–角度 14 + 弹簧引导示例
–反应 + 弹簧启动示例





 

源代码

您可以在Github 上找到本教程的完整源代码。

改用 JPQL:
Spring JPA @Query Spring Boot 中 JPQL 的示例

或派生查询:
Spring Boot 中的 Spring JPA 派生查询示例

或 EntityManager:
Spring Boot 中的 JPA EntityManager 示例

关联:
–JPA 在春季引导中使用休眠的一对一示例–使用休眠和春季引导的 JPA 一对多示例–JPA 多对多示例与春季引导

中的休眠示例

您可以在以下教程中应用此实现:
–Spring JPA + H2 示例–Spring JPA + MySQL 示例–Spring JPA + PostgreSQL 示例–Spring JPA + Oracle 示例–Spring JPA + SQL Server 示例

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/40540.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

动态SQL

动态SQL 可以根据具体的参数条件&#xff0c;来对SQL语句进行动态拼接。比如在以前的开发中&#xff0c;由于不确定查询参数是否存在&#xff0c;许多人会使用类似于where 1 1 来作为前缀&#xff0c;然后后面用AND 拼接要查询的参数&#xff0c;这样&#xff0c;就算要查询的…

MongoShake数据灾备与迁移

安装部署 解压 建议部署在离目标端近的地方&#xff0c;比如部署再目标端本地 tar -zxvf mongo-shake-v2.8.1.tgz配置 同构环境下主要参数 启动 执行下述命令启动同步任务&#xff0c;并打印日志信息&#xff0c;-verbose 0表示将日志打印到文件&#xff0c;在后台运行 …

【Linux从入门到放弃】Linux基本指令大全

&#x1f9d1;‍&#x1f4bb;作者&#xff1a; 情话0.0 &#x1f4dd;专栏&#xff1a;《Linux从入门到放弃》 &#x1f466;个人简介&#xff1a;一名双非编程菜鸟&#xff0c;在这里分享自己的编程学习笔记&#xff0c;欢迎大家的指正与点赞&#xff0c;谢谢&#xff01; L…

黑苹果之微星(MSI)主板BIOS详细设置篇

很多童鞋安装黑苹果的时候会卡住&#xff0c;大部分原因是cfg lock 没有关闭&#xff0c;以及USB端口或SATA模式设置错误。 为了避免这些安装阶段报错的情况发生&#xff0c;今天给大家分享一下超详细的BIOS防踩坑设置指南--微星&#xff08;MSI&#xff09;主板BIOS篇&#xf…

springcloud总结篇

一.整体结构 springcloud总体架构 对比学习 二.具体 1.场景模拟 订单服务调用库存服务来更新数据库中的库存 2.springcloud问题解析 Eureka OpenFeign &#xff08;RibbonRestTemplate&#xff09; Hystrix Gateway config Bus 订单服务只知道库存服务的名称…

Python测试-unittest,2022-11-27

(2022.11.27 Sun) unittest是Python自带的单元测试框架。unittesthtml和pytestallure(测试报告)成为常用的自动测试和报告的框架组合。 unittest-archi-2022-11-23-2114.png 概念 test case测试用例&#xff1a;测试用例是测试的基本单元&#xff0c;用于测试一组特定输入的特…

OpenCV图像特征提取学习四,SIFT特征检测算法

一、SIFT特征检测概述 SIFT的全称是Scale Invariant Feature Transform&#xff0c;尺度不变特征变换&#xff0c;由加拿大教授David G.Lowe提出的。SIFT特征具有对旋转、尺度缩放、亮度变化等保持不变性&#xff0c;是一种非常稳定的局部特征。 1.1 SIFT算法具的特点 图像…

平衡搜索树——AVL树小记

文章目录二叉搜索树平衡搜索树AVL树定义AVL中平衡(Balance)因子的定义AVL树插入规则AVL树失衡情况左左失衡/右右失衡左右失衡RL失衡代码左旋-调整平衡插入调整平衡因子AVL树正确性的验证二叉搜索树 理想情况下&#xff0c;二叉搜索树的查找时间复杂度是0(log(n)) 但是&#xff…

Linux 进程概念 —— 初识操作系统(OS)

文章目录1. 概念2. 设计操作系统的目的3. 定位4. 如何理解管理5. 再谈操作系统&#x1f351; 硬件部分&#x1f351; 操作系统&#x1f351; 驱动程序&#x1f351; 用户部分&#x1f351; 系统调用接口&#x1f351; 用户接口操作6. 总结1. 概念 任何计算机系统都包含一个基本…

HTML5基础汇总

目录 一&#xff0c;html5文档头部 1.页面标题及字符集的收集 &#xff08;1&#xff09;.title标签 &#xff08;2&#xff09;.charset属性 2.元信息的设置 &#xff08;1&#xff09;.meta标签的作用 &#xff08;2&#xff09;.http-equiv/content &#xff08;2&am…

数据结构堆介绍,图文详解分析——Java/Kotlin双版本代码

堆介绍 堆是一种特殊的树结构。根据根节点的值与子节点值的大小关系&#xff0c;堆又分为最大堆和最小堆。 最大堆&#xff1a;每个节点的值总是大于或者等于其任意子节点的值。所以最大堆中根节点即为最大值。 最小堆&#xff1a;每个节点的值总是小于或者等于其任意子节点…

第六章课后题(LSTM | GRU)

目录习题6-3 当使用公式(6.50)作为循环神经网络得状态更新公式时&#xff0c;分析其可能存在梯度爆炸的原因并给出解决办法.习题6-4 推导LSTM网络中参数的梯度&#xff0c;并分析其避免梯度消失的效果​编辑习题6-5 推导GRU网络中参数的梯度&#xff0c;并分析其避免梯度消失的…

集合框架----源码解读Vector篇

1.vector官方简绍 Vector类实现了一个可增长的对象数组。与数组一样&#xff0c;它包含可以使用整数索引访问的组件。但是&#xff0c;Vector的大小可以根据需要增加或缩小&#xff0c;以适应在创建Vector之后添加和删除项。 每个向量都试图通过维护一个容量和一个capacityIncr…

C#设计模式详解(2)——Factory Method(工厂方法)

文章目录C#设计模式详解(2)——Factory Method&#xff08;工厂方法&#xff09;工厂方法模式1.1 概念1.2 意图1.3 问题1.4 解决方案1.5 工厂方法模式结构1.6 案例代码1.7 游戏开发中的应用C#设计模式详解(2)——Factory Method&#xff08;工厂方法&#xff09; 工厂方法模式…

领悟《信号与系统》之 非周期信号的傅里叶变换

非周期信号的傅里叶变换一、非周期信号的傅里叶变换二、 典型信号的傅立叶变换1.单边指数信号2.偶双边指数3. 矩阵脉冲信号4. 奇双边指数5. 符号函数6. 冲激信号7. 阶跃信号三、常用傅里叶变换表这里记录的信号都是非周期信号的傅里叶变化&#xff0c;频谱变换的特点就是&#…

【计算机网络】数据链路层:使用广播信道的数据链路层(1)

局域网的数据链路层 局域网特点&#xff1a;网络为一个单位所拥有&#xff0c;地理范围和站点数目均有限。 地理范围和站点数目均有限。 局域网优点&#xff1a; 具有广播功能&#xff0c;从一个站点可以很方便地访问全网。 便于系统的拓展和演变&#xff0c;各设备的位置…

Discourse 论坛激活邮件问题

根据 Discourse 的官方推荐&#xff0c;我们使用的是 MailGun 的服务。 在大部分情况下都没有问题&#xff0c;但是在一些特定的邮件地址&#xff0c;例如 iCloud&#xff0c;我们在发送激活邮件的时候有提示为&#xff1a; "message": "5.5.1 Error: need MA…

实验:温湿度数据oled显示

OK,本次介绍一个oled实验 本来只想做oled实验的 后面想想这个实验太简单 就加上了温湿度传感器 oled可以打印英文和数字,比如用display.println(“Hello World!”)就可以了 如果打印汉字就比较复杂了 需要相应的软件,生成编码 然后一个字一个字打印 不过只要汉字不…

【数据结构】树——二叉树

1.树的介绍以及树的基本概念和性质 2.二叉树介绍以及二叉树的性质 3.二叉树的构建&#xff1a;穷举创建&#xff0c;递归创建 4.二叉树的基本操作 之前我们介绍了顺序表&#xff0c;链表&#xff0c;以及栈和队列&#xff0c;这几种数据结构都属于线性结构&#xff0c;而我们接…

GreenPlum/PostGreSQL表锁处理

GreenPlum/PostGreSQL表锁处理 数据库中遇到表锁的情况&#xff0c;可以通过select * from pg_stat_activity;查看表锁的进程及进程ID&#xff0c;从而取消进程&#xff0c;解锁。 一、模拟表锁 1.1 模拟表数据 创建lock_test表&#xff0c;并随意插入一条数据&#xff0c;…