【发布时间】:2013-12-10 21:12:54
【问题描述】:
如何使用 JPA 过滤 MySQL 数据库中的行,忽略 MySQL 中给定 DateTime 字段的时间部分?
例如,以下代码段计算数据库表中位于 MySQL 中 DateTime 类型列中给定的两个日期之间的行数。
CriteriaBuilder criteriaBuilder=entityManager.getCriteriaBuilder();
CriteriaQuery<Long>criteriaQuery=criteriaBuilder.createQuery(Long.class);
Root<Discount> root = criteriaQuery.from(entityManager.getMetamodel().entity(Discount.class));
criteriaQuery.select(criteriaBuilder.countDistinct(root));
DateTimeFormatter dateTimeFormatter=DateTimeFormat.forPattern("dd-MMM-yyyy hh:mm:ss aa");
DateTime firstDate = dateTimeFormatter.parseDateTime("01-Oct-2013 11:34:26 AM").withZone(DateTimeZone.UTC);
DateTime secondDate = dateTimeFormatter.parseDateTime("31-Oct-2013 09:22:23 PM").withZone(DateTimeZone.UTC);
criteriaQuery.where(criteriaBuilder.between(root.get(Discount_.discountStartDate), firstDate, secondDate));
Long rowCount = entityManager.createQuery(criteriaQuery).getSingleResult();
firstDate 和secondDate 这两个参数将依次是动态的。
如何重写此查询,以便比较不包括 SQL 查询中要委托给 MySQL 的时间部分。
实体Discount中的discount_start_date列指定如下。
@Column(name = "discount_start_date")
@Type(type="org.jadira.usertype.dateandtime.joda.PersistentDateTime")
private DateTime discountStartDate;
【问题讨论】:
-
真的需要委托给mysql吗?如果没有,您可以在
DateTime.withMillisOfDay(0)和DateTime.withMillisOfDay(0).plusDays(1).plusMillis(-1)之间使用 -
@samlewis 比
withMillisOfDay更好的是withTimeAtStartOfDay。并非每个时区的每一天都有午夜,因此最好避免以午夜为导向的数学。 “withTimeAtStartOfDay”被添加到Joda-Time 以处理夏令时或其他可能改变一天开始的问题。 -
withMillisOfDay(0)和withTimeAtStartOfDay()都生成类似[2013-10-02 05:30:00.0, 2013-11-01 05:29:59.999]的日期。实际上,应该完全避免时间部分。这可能吗?它应该对应于这个 MySQL 查询 -select count(*) as cnt from discount where date(discount_start_date) between '2013-10-02' and '2013-11-01'。
标签: mysql datetime jpa criteria jodatime