antongarakh
antongarakh

Reputation: 690

Spring Data JPA: Sort only by date part of java.time.LocalDateTime column

Entity:

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;
import java.util.UUID;

@Table( name = "order" )
public class Order
{
    @Id
    @Column( name = "id", columnDefinition = "BINARY(16)" )
    private UUID id;

    @Column( name = "posting_date" )
    private LocalDateTime postingDate;

    @Column( name = "created" )
    private LocalDateTime created;

}

To search with sorting org.springframework.data.jpa.repository.JpaSpecificationExecutor#findAll(org.springframework.data.jpa.domain.Specification<T>, org.springframework.data.domain.Pageable) is used

Due to specific case I have to sort by two fields: postingDate and created and treat postingDate as date (not datetime like it is defined in entity), but I don't know how.

To make such a request to MySQL DB, DATE() function should be used, like this:

select
        order.*
    from
        order o
    where
      ...
    order by
        date(o.posting_date) desc,
        o.pae_created desc

But I want to use JPA methods to search and sort.

Question: Is there any way to tell JPA that this or that column to sort should be wrapped with some function? How to do so?

Upvotes: 1

Views: 1461

Answers (1)

Nikos Paraskevopoulos
Nikos Paraskevopoulos

Reputation: 40308

This is, in principle doable. I did not run the following code though! Additionally, the function keyword was added to JPA 2.1, if you are using an earlier version this will probably not work.

JPQL:

SELECT o FROM Order o WHERE ...
ORDER BY
  function('DATE', o.postingDate) DESC,
  o.created DESC

This is also supported by the Criteria API.

Upvotes: 1

Related Questions