Spring Data查询DateTime只有日期 [英] Spring Data Querying DateTime with only Date
问题描述
我有这个数据模型
public class CustomerModel{
@Column
@Type(type="org.joda.time.contrib.hibernate.PersistentDateTime")
private DateTime membershipDate;
//Other properties and getters
}
以及以下回购
public interface CustomerRepo extends Repository<CustomerModel, Long>{}
我想做的是.检索给定日期的所有用户,例如(2013 年 8 月 1 日加入的成员),但问题是在我的数据库上,membershipDate 有时间.如何忽略时间并检索给定日期的所有用户?
What I want to do is. Retrieve all users on a given date eg(Members that Joined in August 1 2013) however the problem is that on my DB the membershipDate has a time with it. how can I ignore the time and retrieve all users on a given date?
推荐答案
不幸的是,对于 JodaTime,唯一的解决方法是使用 Between
关键字并使用两个 DateTime
实例起那一天.
Unfortunately with JodaTime the only way around this is using the Between
keyword and use two DateTime
instances making up the day.
interface CustomerRepo extends Repository<CustomerModel, Long>{
List<CustomerModel> findByMemberShipDateBetween(DateTime start, DateTime end);
}
如果你的领域模型在内部使用了 Java Date
s 你可以使用这种风格:
If your domain model used Java Date
s internally you could've used this style:
interface CustomerRepo extends Repository<CustomerModel, Long>{
List<CustomerModel> findByMemberShipDate(@Temporal(TemporalType.DATE) Date date);
}
不是 @Temporal
注释是自定义 Spring Data JPA 注释,因为当前不允许在参数上使用普通 JPA 注释.不幸的是,这仅适用于 Java Date
的原因是当前 JPAPI 的限制.Query
上的 setParameter(…)
方法只为 Date
类型的参数接受一个 TemporalType
.我们可以尝试在参数绑定上转换 JodaTime 对象,但我猜持久性提供者会因为类型不匹配而拒绝它(Date
VS.DateTime
).
Not the @Temporal
annotation is a custom Spring Data JPA one as the plain JPA one is currently not allowed on parameters. The reason that this only works with Java Date
s unfortunately is a limitation of the current JPAPIs. The setParameter(…)
method on Query
only takes a TemporalType
for parameters of type Date
. We could try converting the JodaTime objects on parameter binding but I guess the persistence providers will reject that due to the type mismatch then (Date
VS. DateTime
).
这篇关于Spring Data查询DateTime只有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!