等效于Spring数据中的IQueryable [英] Equivalent of IQueryable in Spring Data
问题描述
我习惯于.Net和LINQtoEntities,尤其是IQueryable部分,该部分允许在获取结果之前通过不同的函数传递请求.
I'm used to .Net and LINQtoEntities, especially the IQueryable part which allows to carry a request through different functions before fetching the results.
spring数据中是否存在类似的内容?还是其他任何Java ORM?
Does anything like this exist in spring data ? Or any other java ORM ?
我想做的基本例子:
private IQueryable<Todo> GetAll(){
context.Todos.Where(t => !t.Deleted);
}
public IEnumerable<Todo> GetDoneTodos(){
GetAll().Where(t => t.Done).ToList();
}
推荐答案
您可以使用Spring Data的 QueryDSL 集成.基本上,您在存储库接口中扩展了QueryDslPredicateExecutor
,并添加了一个findAll
方法来获取QueryDSL Predicate
并基于该Predicate
过滤所有结果.假设我们有一个域对象,例如Greeting
,那么我们将拥有这样的存储库:
You can use Spring Data's QueryDSL integration. Basically, you extend the QueryDslPredicateExecutor
in your repository interface and it add a findAll
method that gets a QueryDSL Predicate
and filter all the results based on that Predicate
. Suppose we have domain object, say Greeting
, then we'd have repository like this:
public interface GreetingRepository extends QueryDslPredicateExecutor<Greeting> {}
然后,您可以使用QueryDSL生成的生成的QModel
创建Predicate
并将其传递给我们的greetingRepository
.假设我们要由一个特定用户过滤所有Greeting
:
Then you can use generated QModel
s generated by QueryDSL to create a Predicate
and pass it to our greetingRepository
. Suppose we're going to filter all the Greeting
s by one specific user:
Predicate filterByUser = greeting.user.eq(someUser);
greetingRepository.findAll(filterByUser);
greeting
是QueryDSL根据我们的Greeting
模型生成的元模型.
greeting
is a metamodel generated by QueryDSL based on our Greeting
model.
注释1 :您可以看到如何集成Spring Data和QueryDSL
Note 1: You can see how you can integrate Spring Data and QueryDSL here and see more examples for QueryDSL's Predicate
s here.
注释2 :QueryDslPredicateExecutor
还提供了findOne(Predicate predicate)
,count(Predicate predicate)
和exists(Predicate predicate)
方法,这些方法当然是有用的并且不言自明.
Note 2: QueryDslPredicateExecutor
also provides findOne(Predicate predicate)
, count(Predicate predicate)
and exists(Predicate predicate)
methods which are useful and self-explanatory, of course.
注释3 :使用Specification
可以实现几乎相同的功能,但是在我的设备中QueryDSL具有更优雅和可读性的Predicate
s.
Note 3: You can achieve almost the same thing with Specification
s but in my opnion QueryDSL has more elegant and readable Predicate
s.
这篇关于等效于Spring数据中的IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!