Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query with sort() and limit() in Spring Repository interface

I'm new to Spring Data with MongoDB and would like to have an automagically generated query method inside my MongoRepository extension interface which requires filtering, sorting and limiting.

The query looks like this:

// 'created' is the field I need to sort against

find({state:'ACTIVE'}).sort({created:-1}).limit(1)

The repository interface looks like this:

public interface JobRepository extends MongoRepository<Job, String> {
    @Query("{ state: 'ACTIVE', userId: ?0 }")
    List<Job> findActiveByUserId(String userId);

    // The next line is the problem, it wont work since
    // it's not in the format @Query expects
    @Query("find({state:'ACTIVE'}).sort({created:-1}).limit(1)")
    Job findOneActiveOldest();

    ...
}

I know that one can add a Sort argument to a query method in order to get sorting but the problem is limiting the results to just a single object. Is this possible to do without having to write a custom JobRepositoryImpl?

Thanks

Edit:

Example of what I am looking for:

@Query("{ state:'ACTIVE', $orderby: {created:-1}, $limit:1 }")
Job findOneActiveOldest();

or

@Query("{ state:'ACTIVE' }")
@Sort("{ created:-1 }")
@Limit(1)
Job findOneActiveOldest();

But this obviously doesn't work :(

like image 266
m1h4 Avatar asked Apr 08 '12 22:04

m1h4


People also ask

How do I limit records in JPA repository?

JPA Setup In our repository method, we use the EntityManager to create a Query on which we call the setMaxResults() method. This call to Query#setMaxResults will eventually result in the limit statement appended to the generated SQL: select passenger0_.id as id1_15_, passenger0_.

Is it possible to define a sort type in @query annotation using Spring JPA?

Spring Data JPA allows you to add a special Sort parameter to your query method. The Sort class is just a specification that provides sorting options for database queries. By using dynamic sorting, you can choose the sorting column and direction at runtime to sort the query results.

How do you write limits in JPA?

Spring Data JPA supports keywords 'first' or 'top' to limit the query results (e.g. findTopBy....). An optional numeric value can be appended after 'top' or 'first' to limit the maximum number of results to be returned (e.g. findTop3By....). If this number is not used then only one entity is returned.


2 Answers

What's wrong with:

public interface JobRepository extends MongoRepository<Job, String> {

  @Query("{ state : 'ACTIVE' }")
  Page<Job> findOneActiveOldest(Pageable pageable);
}

and using it:

// Keep that in a constant if it stays the same
PageRequest request = new PageRequest(0, 1, new Sort(Sort.Direction.DESC, "created"));
Job job = repository.findOneActiveOldest(request).getContent().get(0);
like image 80
Oliver Drotbohm Avatar answered Oct 02 '22 13:10

Oliver Drotbohm


Just adding a correction to Oliver's answer, it's Direction.DESC and not Directions.DESC and the order of the params is wrong.

Change :

PageRequest request = new PageRequest(0, 1, new Sort("created", Directions.DESC));

to:

PageRequest request = new PageRequest(0, 1, new Sort(Direction.DESC, "created"));
like image 29
Marc Avatar answered Oct 02 '22 12:10

Marc