英文:
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 a specific case, I have to sort by two fields: postingDate
and created
and treat postingDate
as a date (not datetime like it is defined in the entity), but I don't know how.
To make such a request to the MySQL DB, the 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?
英文:
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?
答案1
得分: 1
这从原则上是可行的。但我并没有运行以下的代码!另外,function
关键字是在 JPA 2.1 中添加的,如果你使用的是早期版本,这可能不起作用。
JPQL:
SELECT o FROM Order o WHERE ...
ORDER BY
function('DATE', o.postingDate) DESC,
o.created DESC
这在 Criteria API 中也是支持的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论