等效于Spring数据中的IQueryable [英] Equivalent of IQueryable in Spring Data

查看:59
本文介绍了等效于Spring数据中的IQueryable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于.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 QModels generated by QueryDSL to create a Predicate and pass it to our greetingRepository. Suppose we're going to filter all the Greetings 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 Predicates 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 Specifications but in my opnion QueryDSL has more elegant and readable Predicates.

这篇关于等效于Spring数据中的IQueryable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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