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

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

问题描述

我是Spring数据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查询放在包装我的repo的服务层。

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谓词))的能力,因为我没有我可以访问实际的repo对象,在第二种情况下,我将查询逻辑放在服务层而不是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数据?

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?

谢谢!

Eric

推荐答案

可能最方便的方法是让您的存储库接口只需扩展 QueryDslPredicateExecutor 将Querydsl Predicate 对象简单地传输到存储库并单独执行或与 Pageable 排序等。

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.

如果你真的想隐藏谓词组合到存储库层(这绝对没问题但实际上是服务的)你创建了一个单独的存储库实现类,如上所述此处并使用 QueryDslRepositorySupport 作为基类。在您实现的finder方法中,您可以使用<(c)中的更新(...) 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天全站免登陆