13

我有这个数据模型

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 有时间。如何忽略时间并检索给定日期的所有用户?

4

3 回答 3

36

不幸的是,使用 JodaTime 解决此问题的唯一方法是使用Between关键字并使用两个DateTime实例来弥补这一天。

interface CustomerRepo extends Repository<CustomerModel, Long>{

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

如果您的域模型Date在内部使用 Java,您可以使用这种样式:

interface CustomerRepo extends Repository<CustomerModel, Long>{

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

不是@Temporal注释是自定义 Spring Data JPA 之一,因为当前不允许在参数上使用普通 JPA 之一。不幸的是,这只适用于 JavaDate的原因是当前 JPAPI 的限制。setParameter(…)on 方法Query只接受一个TemporalTypefor 类型的参数Date。我们可以尝试在参数绑定上转换 JodaTime 对象,但我猜持久性提供者会因为类型不匹配(DateVS. DateTime)而拒绝它。

于 2013-08-06T17:10:56.400 回答
5

您可以采取一些解决方法:创建 DateTime dayBegin 和 DateTime dayEnd 例如 2013-07-04 00:00:00 和 2013-07-04 23:59:59 并通过查询获取所需的对象:

List<CustomerModel> findByMembershipBetween(DateTime dayBegin, DateTime dayEnd);
于 2013-08-15T13:16:20.477 回答
3

jODA 和 spring & JPA 其实是好朋友,看看:

http://blog.netgloo.com/2015/04/06/spring-boot-using-joda-time-on-jpa-entity-with-hibernate/

请享用

于 2016-01-26T15:48:34.063 回答