将 Spring 数据查询生成器与 Spring 数据 JPA 规范相结合?

Combining Spring Data query builder with Spring Data JPA Specifications?

Spring Data 允许您在存储库界面中声明类似 findByLastname() 的方法,它会自动为您从方法名称生成查询。

是否有可能以某种方式让这些自动生成的查询也接受规范,以便在数据返回之前对其进行额外的限制?

这样,我可以调用 findByLastname("Ted", isGovernmentWorker()),这将找到所有姓氏为 Ted 并且满足 isGovernmentWorker() 规范的用户。

我需要这个,因为我想要 Spring Data 提供的自动查询创建,因为我仍然需要能够在运行时应用任意规范。

Spring 数据允许您实现自定义存储库并使用规范或 QueryDSL。

请参阅 this 文章。

所以最后您将有一个 YourCustomerRepository 和适当的 YourRepositoryImpl 实现,您将在其中放置您的 findByLastname("Ted", isGovernmentWorker()) 方法。 然后 YourRepository 应该扩展 YourCustomerRepository 接口。

没有这样的功能。规范只能应用于 JpaSpecificationExecutor 操作。

更新 数据访问操作由代理生成。因此,如果我们想在单个 SELECT 调用中对操作进行分组(如 findByName + Criteria),代理必须理解并支持这种用法;它没有。

使用规范 API 时的预期用途对于您的情况如下所示:

findAll(Specifications.where(hasLastName("Ted")).and(isGovernmentWorker())