2013-08-06 47 views
9

我有这个数据模型春数据查询日期时间只有日期

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日加入的成员),但问题是在我的DB上,membershipDate有一段时间。我怎么能忽略时间和检索给定日期的所有用户?

回答

28

不幸的是,与JodaTime有关的唯一方法是使用Between关键字并使用两个DateTime实例组成当天。

interface CustomerRepo extends Repository<CustomerModel, Long>{ 

    List<CustomerModel> findByMemberShipDateBetween(DateTime start, DateTime end); 
} 

如果使用的Java Date你的域模型内部就是你可能已经使用这种风格:

interface CustomerRepo extends Repository<CustomerModel, Long>{ 

    List<CustomerModel> findByMemberShipDate(@Temporal(TemporalType.DATE) Date date); 
} 

不是@Temporal注释是一个自定义的春天JPA的数据作为一个普通的JPA一个目前不允许参数。这仅适用于Java Date的原因很不幸是当前JPAPI的限制。在Query上的setParameter(…)方法仅需要TemporalType用于Date类型的参数。我们可以尝试在参数绑定上转换JodaTime对象,但是我想持久化提供者会因为类型不匹配而拒绝(Date VS. DateTime)。

+2

在spring-data的v1.6.2中,此注释仅支持java.util.Date类型的参数。因此,此解决方案目前不适用于比较DateTime对象。当前的javadocs位于[here](http://docs.spring.io/spring-data/jpa/docs/current/api/org/springframework/data/jpa/repository/Temporal.html)。 – yurodivuie

+0

@yurodivuie - 这是一个伟大的捕获。感谢指针。我更新了答案,为JodaTime提供了一个替代解决方案,并概述了为什么它目前仅适用于Java Date类型。 –

+0

实体中的Java 8 ZonedDateTime和作为搜索参数的LocalDate如何? –

3

你可以做一些解决方法:创建DateTime dayBegin和DateTime dayEnd,例如通过查询2013年7月4日00:00和2013年7月4日23:59:59,并获取需要的对象:

List<CustomerModel> findByMembershipBetween(DateTime dayBegin, DateTime dayEnd); 
-4

您需要使用DATE函数

比较两个日期并忽略时间

WHERE DATE(dbdDate) = DATE(yourDate)