Using dates in Query where where criteria

I have an object with a field java.util.Datesaved as TemporalType.DATE. When passing java.util.Datewith hours, minutes, or seconds to the where clause of a criteria request, I cannot get a match from the database.

Customization is an embedded H2 database in Spring with Hibernate. I tried using PostgreSQL instead of H2 and it works. I also tried installing H2 in PostgreSQL mode, but it doesn't change anything.

Given an object

@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;
    }
}

The following query returns a match if the hours, minutes, and seconds of the parameter are set to 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(); 
}

The following is a complete example. The test failed in the last statement, where I query the database using Dates with the hours, minutes, and seconds set.

@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();
}
+4
1

, :

Restrictions .

0

Source: https://habr.com/ru/post/1546974/


All Articles