问题
I'm used to .Net and LINQtoEntities, especially the IQueryable part which allows to carry a request through different functions before fetching the results.
Does anything like this exist in spring data ? Or any other java ORM ?
Basic example of what I'd like to be able to do :
private IQueryable<Todo> GetAll(){
context.Todos.Where(t => !t.Deleted);
}
public IEnumerable<Todo> GetDoneTodos(){
GetAll().Where(t => t.Done).ToList();
}
回答1:
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> {}
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
is a metamodel generated by QueryDSL based on our Greeting
model.
Note 1: You can see how you can integrate Spring Data and QueryDSL here and see more examples for QueryDSL's Predicate
s here.
Note 2: QueryDslPredicateExecutor
also provides findOne(Predicate predicate)
, count(Predicate predicate)
and exists(Predicate predicate)
methods which are useful and self-explanatory, of course.
Note 3: You can achieve almost the same thing with Specification
s but in my opnion QueryDSL has more elegant and readable Predicate
s.
来源:https://stackoverflow.com/questions/34862757/equivalent-of-iqueryable-in-spring-data