Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring CRUD repository: is there findOneByMaxXYZColumn()?

Tags:

spring-data

My requirement:

fetch ONE object (e.g RetainInfo ) from table RETAIN_INFO if VERSION column has max value

Does CRUD repository support for an interface method like

findOneByMaxRetVersionAndCountry("DEFAULT") 

Equivalent db2 sql:

select RET_ID, max(ri.RET_VERSION) from RETAIN_INFO ri  where ri. COUNTRY='DEFAULT'  group by RET_ID  fetch first 1 rows only; 
  • This query selects an ID, but I would actually want the RetainInfo object corresponding the SINGLE row returned by the query.

I prefer to get that without using custom query, i.e using findBy or some other method/interface supported by Spring CRUD.

like image 271
Espresso Avatar asked Apr 02 '14 03:04

Espresso


People also ask

Which is better JPA or CRUD repository?

It provides only CRUD functions like findOne, saves, etc. JPA repository also extends the PagingAndSorting repository. It provides all the method for which are useful for implementing pagination. Crud Repository doesn't provide methods for implementing pagination and sorting.

Is CRUD repository part of Spring data JPA?

Here in the following image Repository, CrudRepository and PagingAndSortingRepository belong to Spring Data Commons whereas JpaRepository belongs to Spring Data JPA. It is a base interface and extends Repository Interface. It extends PagingAndSortingRepository that extends CrudRepository.

What is difference between PagingAndSortingRepository and JpaRepository?

PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.


2 Answers

You could use limiting in combination with sorting (spring data reference:limit query results). Declare a method similar to the following in your CrudRepository interface :

RetainInfo findTopByCountryOrderByRetVersionDesc(String country); 
like image 179
CoSeeWolf Avatar answered Oct 09 '22 13:10

CoSeeWolf


You can also use findFirst to get the first result. Before getting the result, make sure to use Orderby and then the ascending(Asc) or descending(Desc). As an example if you want to order by version and retrieve based on productName

RetainInfo findFirstByProductNameOrderByVersionDesc(String productName); 
like image 40
drafterr Avatar answered Oct 09 '22 13:10

drafterr