Spring Data仅使用Date查询DateTime
我有这个数据模型
public class CustomerModel{ @Column @Type(type="org.joda.time.contrib.hibernate.PersistentDateTime") private DateTime membershipDate; //Other properties and getters }
以下回购
public interface CustomerRepo extends Repository{}
我想做的是。 检索给定日期的所有用户,例如(2013年8月1日加入的成员)但问题是在我的数据库中,membershipDate有时间。 如何忽略时间并检索给定日期的所有用户?
不幸的是,对于JodaTime,唯一的解决方法是使用Between
关键字并使用两个DateTime
实例组成一天。
interface CustomerRepo extends Repository{ List findByMemberShipDateBetween(DateTime start, DateTime end); }
如果您的域模型在内部使用Java Date
您可以使用此样式:
interface CustomerRepo extends Repository{ List findByMemberShipDate(@Temporal(TemporalType.DATE) Date date); }
@Temporal
注释不是自定义的Spring Data JPA,因为普通的JPA注释目前不允许参数。 不幸的是,这仅适用于Java Date
的原因是当前JPAPI的限制。 Query
上的setParameter(…)
方法仅为Date
类型的参数采用TemporalType
。 我们可以尝试在参数绑定上转换JodaTime对象,但我想持久性提供程序将拒绝由于类型不匹配( Date
VS. DateTime
)。
你可以做一些解决方法:创建DateTime dayBegin和DateTime dayEnd,例如2013-07-04 00:00:00和2013-07-04 23:59:59并通过查询获取所需的对象:
List findByMembershipBetween(DateTime dayBegin, DateTime dayEnd);
jODA和spring&JPA实际上是好朋友,只需明白:
http://blog.netgloo.com/2015/04/06/spring-boot-using-joda-time-on-jpa-entity-with-hibernate/
请享用
您需要使用DATE函数
比较两个日期并忽略时间
WHERE DATE(dbdDate) = DATE(yourDate)