在本教程中,您将了解如何在 Spring Boot 示例中使用 Spring JPA @Query进行自定义查询。我将向您展示:
- 使用JPQL(Java持久性查询语言)的方法
- 如何在 Spring 引导中执行 SQL 查询
- 具有 WHERE 条件的 JPA 选择查询示例
内容
- JPQL 与本机查询
- Spring JPA @Query Spring Boot 的示例
- 创建和设置 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();
JPQL 仅支持 SQL 标准的子集。如果要进行复杂的查询,请查看本机 SQL 查询。
这是如何在 Spring Boot 中执行 SQL 查询的方法,带有@Query
注释:
@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);
有关更多详细信息,请访问:
使用 Spring 引导的 JPA 本机查询示例
让我们看看我们如何在 Spring Boot 中使用 JPA 和 JPQL 示例进行自定义查询。
Spring JPA @Query Spring Boot 的示例
–科技:
- Java 8
- Spring Boot 2.6.3 (with Spring Data JPA)
- MySQL/PostgreSQL/H2 (embedded database)
- Maven 3.8.1
– 项目结构:
让我简要解释一下。
Tutorial
数据模型类对应于实体和表tutorials。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、NetBeans、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
MySQL5InnoDBDialect
或 PostgreSQLPostgreSQLDialect
spring.jpa.hibernate.ddl-auto
用于数据库初始化。我们将值设置为值update
,以便在数据库中自动创建一个与定义的数据模型对应的表。对模型的任何更改也将触发对表的更新。对于生产,此属性应该是validate
。
– 对于 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,因此默认 urlhttp://localhost:8080/h2-console
将更改为http://localhost:8080/h2-ui
。
创建实体
在model 包中,我们定义类Tutorial
。
教程有六个字段:id, title, level, description, published, createdAt。
model/Tutorial.java
package com.bezkoder.spring.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.query.repository;
import com.bezkoder.spring.query.model.Tutorial;
public interface TutorialRepository extends JpaRepository<Tutorial, Long> {
}
在此接口中,我们将编写 JPA Select 查询(带有 where 条件)以从数据库中获取数据。
我将向您展示如何在 Spring Boot 中使用 JPQL 查询示例。
假设我们已经有了这样的tutorials 表:
JPA 选择查询,WHERE条件示例
让我们使用@Query
注释来创建带有 SELECT 和 WHERE 关键字的 Spring JPA 查询。
@Query("SELECT t FROM Tutorial t")
List<Tutorial> findAll();
@Query("SELECT t FROM Tutorial t WHERE t.published=?1")
List<Tutorial> findByPublished(boolean isPublished);
@Query("SELECT t FROM Tutorial t WHERE t.title LIKE %?1%")
List<Tutorial> findByTitleLike(String title);
@Query("SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%'))")
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 查询大于或等于
春季数据 JPA 查询大于或等于日期/列:
@Query("SELECT t FROM Tutorial t WHERE t.level >= ?1")
List<Tutorial> findByLevelGreaterThanEqual(int level);
@Query("SELECT t FROM Tutorial t WHERE t.createdAt >= ?1")
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 BETWEEN查询
春季数据JPA查询 日期/列之间:
@Query("SELECT t FROM Tutorial t WHERE t.level BETWEEN ?1 AND ?2")
List<Tutorial> findByLevelBetween(int start, int end);
@Query("SELECT t FROM Tutorial t WHERE t.createdAt BETWEEN ?1 AND ?2")
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("SELECT t FROM Tutorial t WHERE t.published=:isPublished AND t.level BETWEEN :start AND :end")
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 查询Order By Desc/Asc
Spring 数据 JPA 查询顺序按列进行筛选的示例:
@Query("SELECT t FROM Tutorial t ORDER BY t.level DESC")
List<Tutorial> findAllOrderByLevelDesc();
@Query("SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%')) ORDER BY t.level ASC")
List<Tutorial> findByTitleOrderByLevelAsc(String title);
@Query("SELECT t FROM Tutorial t WHERE t.published=true ORDER BY t.createdAt DESC")
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 查询Sort By
使用带有过滤的Sort
类的 Spring 数据 JPA 查询示例:
@Query("SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', ?1,'%'))")
List<Tutorial> findByTitleAndSort(String title, Sort sort);
@Query("SELECT t FROM Tutorial t WHERE t.published=?1")
List<Tutorial> findByPublishedAndSort(boolean isPublished, Sort sort);
结果:
tutorials = tutorialRepository.findByTitleAndSort("at", Sort.by("level").descending());
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=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.findByTitleAndSort("at", Sort.by("createdAt").descending());
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=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]
*/
tutorials = tutorialRepository.findByPublishedAndSort(false, Sort.by("level").descending());
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("SELECT t FROM Tutorial t")
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 数据 JPA 查询,用于更新实体,同时使用:@Query
@Transactional
@Modifying
@Transactional
@Modifying
@Query("UPDATE Tutorial t SET t.published=true WHERE t.id=?1")
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.java
CommandLineRunner
TutorialRepository
package com.bezkoder.spring.query;
// import ...
@SpringBootApplication
public class SpringBootQueryExampleApplication implements CommandLineRunner {
@Autowired
TutorialRepository tutorialRepository;
public static void main(String[] args) {
SpringApplication.run(SpringBootQueryExampleApplication.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);
}
}
结论
今天我们已经知道如何使用 JPQL 在 Spring Boot 示例中使用 Spring JPA @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 上找到本教程的完整源代码。
改用本机查询:Spring JPA 本机查询示例与
Spring 引导
或派生查询:
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 示例