gpt4 book ai didi

java - 在 Criteria Query where 子句中使用日期

转载 作者:搜寻专家 更新时间:2023-11-01 03:51:50 25 4
gpt4 key购买 nike

我有一个实体,其 java.util.Date 字段存储为 TemporalType.DATE。将包含小时、分钟或秒的 java.util.Date 传递给条件查询的 where 子句时,我似乎无法从数据库中获得匹配项。

该设置是 Spring 中带有 Hibernate 的嵌入式 H2 数据库。我试过使用 PostgreSQL 而不是 H2 并且它有效。我也试过在 PostgreSQL 模式下设置 H2,但它没有改变任何东西。

给定实体

@Entity
public class SomeEntity {

@Id
private int id;

@Temporal(TemporalType.DATE)
private java.util.Date aDate;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public Date getDate() {
return aDate;
}

public void setDate(Date aDate) {
this.aDate = aDate;
}
}

如果参数的小时、分钟和秒已设置为 0,则以下查询仅返回匹配项。

public List<SomeEntity> someQueryOnDate(Date date) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SomeEntity> query = cb.createQuery(SomeEntity.class);

Root<SomeEntity> root = query.from(SomeEntity.class);
Predicate dateEquals = cb.equal(root.get(SomeEntity_.date), date);
query.where(dateEquals);

// This list is always empty if the date in the predicate has a time part
return em.createQuery(query).getResultList();
}

下面是一个完整的例子。测试在最后一个断言上失败,我在其中使用设置了小时、分钟和秒的日期查询数据库。

@Test
public void testDateEquals() throws ParseException {
Date dateWithoutTime = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-03");
Date dateWithTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-07-03 09:45:01");

createEntity(dateWithoutTime);

List<SomeEntity> entitiesMatchingDateWithTime = listAllEntitiesWithDate(dateWithTime);
List<SomeEntity> entitiesMatchingDateWithoutTime = listAllEntitiesWithDate(dateWithoutTime);

Assert.assertFalse("No entities matched the date without time", entitiesMatchingDateWithoutTime.isEmpty());
Assert.assertFalse("No entities matched the date with time" , entitiesMatchingDateWithTime.isEmpty());
}

private void createEntity(Date d) {
SomeEntity entity = new SomeEntity();
entity.setDate(d);
em.persist(entity);

// For good measure
em.flush();
em.clear();
}

private List<SomeEntity> listAllEntitiesWithDate(Date date) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<SomeEntity> query = cb.createQuery(SomeEntity.class);

Root<SomeEntity> root = query.from(SomeEntity.class);
Predicate dateEquals = cb.equal(root.get(SomeEntity_.date), date);
query.where(dateEquals);

return em.createQuery(query).getResultList();
}

最佳答案

也许这里提供了解决方案:

Hibernate Criteria for Dates

您可以使用Restrictions 来比较日期。

关于java - 在 Criteria Query where 子句中使用日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24549607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com