Spring Data仅使用Date查询DateTime

时间:2013-08-06 13:57:40

标签: java spring jpa spring-data spring-data-jpa

我有这个数据模型

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

3 个答案:

答案 0 :(得分:32)

不幸的是,对于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注释不是自定义Spring Data JPA,因为普通的JPA注释目前不允许使用参数。不幸的是,这仅适用于Java Date的原因是当前JPAPI的限制。 setParameter(…)上的Query方法只需TemporalTypeDate类型的参数。我们可以尝试在参数绑定上转换JodaTime对象,但我想持久性提供程序会因为类型不匹配而拒绝(Date VS. DateTime)。

答案 1 :(得分:4)

你可以做一些解决方法:创建DateTime日开始和日期时间日,例如, 2013-07-04 00:00:00和2013-07-04 23:59:59并通过查询获取所需的对象:

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

答案 2 :(得分:3)

jODA和spring&amp; JPA实际上是好朋友,只需参加:

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

享受

相关问题