Spring Data JPA 和 QueryDSL [英] Spring Data JPA and QueryDSL

查看:37
本文介绍了Spring Data JPA 和 QueryDSL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Spring data JPA 的新手,我正在尝试了解如何最好地将它与 QueryDSL 一起使用.如果没有 QueryDSL,我将能够使用 @Query 注释在 SpringData 接口中简单地创建任何查询.

I'm new to Spring data JPA and am trying to understand how to best use it with QueryDSL. Without QueryDSL, I would be able to simply create any queries in my SpringData interface with an @Query annotation.

为了获得使用 QueryDSL 的相同体验,据我所知,我需要创建自己的自定义存储库实现并让我的 repo 接口扩展我的自定义实现接口,或者将所有 QueryDSL 查询放在服务层包装我的回购.

In order to have the same experience using QueryDSL, from what I can see, I need to either create my own custom repository implementation and have my repo interface extend my custom implementation interface or put all my QueryDSL queries at a service layer which wraps my repo.

在第一种情况下,我无法在自定义存储库中使用任何 SD 自动生成的方法(例如: findAll(QueryDSL predicate) ),因为我无法访问实际的存储库对象,而在第二种情况下如果我将查询逻辑放在服务层而不是 repo 层.

In the first case, I lose the ability to use any of the SD autogenerated methods (ex: findAll(QueryDSL predicate) ) in my custom repo since I don't have access to the actual repo object, and in the second case I am putting query logic at the service layer instead of at the repo layer.

这两种解决方案对我来说都不是特别有吸引力.有没有更合适的第三种方式?还是我误解了如何正确使用 QueryDSL 和 Spring Data?

Neither solution sounds particularly attractive to me. Is there a 3rd way that is more appropriate? Or am I misunderstanding how to properly use QueryDSL and Spring Data?

谢谢!

埃里克

推荐答案

可能最方便的方法是让您的存储库接口简单地扩展 QueryDslPredicateExecutor 这增加了简单管道 Querydsl Predicate 的能力 对象到存储库中并单独执行它们或与 PageableSort 等一起执行.

Probably the most convenient way is to let your repository interfaces simply extend QueryDslPredicateExecutor which adds the capability to simply pipe Querydsl Predicate objects into the repository and execute them standalone or alongside Pageable and Sort and the like.

如果您真的想将谓词组合隐藏到存储库层中(这绝对没问题,但实际上用于不同的目的),您可以按照描述创建一个单独的存储库实现类 here 并使用 QueryDslRepositorySupport作为基类.在您实现的查找器方法中,您可以使用基础的 from(...)update(...)delete(...) 方法使用 Querydsl 元模型轻松构建和执行查询.

If you really want to hide the combination of predicates into the repository layer (which is absolutely fine but actually serves a different purpose) you create a separate repository implementation class as described here and use QueryDslRepositorySupport as base class. In your implemented finder methods you can then just use the from(…), update(…) and delete(…) methods of the base class to easily construct and execute queries using the Querydsl meta-model.

这篇关于Spring Data JPA 和 QueryDSL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆