JPA2/Hibernate查询:使用Date作为查询参数忽略"时间"部分

Fab*_* B. 1 hibernate jpa criteria date

我想根据日期字段选择条件查询的一些记录:

CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery();
Root<Macchinario> from = cq.from(Macchinario.class);
cq.select(from);

cq.where(
                    cb.and(
                        cb.like(from.<String>get("marca"), "%"+ricerca.getMarca()+"%"),
                        cb.like(from.<String>get("modello"), "%"+ricerca.getModello()+"%"),
                        cb.like(from.<String>get("matricola"), "%"+ricerca.getMatricola()+"%"),

                        cb.equal(from.get("dataInserimento"), ricerca.getDataInserimento())
                    )
                );
Run Code Online (Sandbox Code Playgroud)

dataInserimento是一个java.util.Date

我正在寻找的"Macchinario"在db中有"2012-05-23 10:16:00".

ricerca.getDataInserimento()返回"2012-05-23 00:00:00".

如何传递该参数,告诉jpa忽略Date的"时间部分"?

JMe*_*nik 6

您可以编写一个util并使用它来截断日期中的时间部分:

DateHelper.java

public static Date getDateWithoutTime(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);
    return cal.getTime();
}
Run Code Online (Sandbox Code Playgroud)

然后改变

cb.equal(from.get("dataInserimento"), ricerca.getDataInserimento())
Run Code Online (Sandbox Code Playgroud)

cb.equal(from.get("dataInserimento"), 
         DateHelper.getDateWithoutTime(ricerca.getDataInserimento()))
Run Code Online (Sandbox Code Playgroud)

更新

从我们从db获得的值截断时间部分似乎无法使用JPA或Hibernate提供的开箱即用功能.Hibernate提供了日期列中的年,月和日值的提取,我们将通过它来实现.

Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(ricerca.getDataInserimento());

Path<Date> dataInserimento = from.get("dataInserimento");
Predicate timelessPredicate = cb.and(
        cb.equal(cb.function("year", Integer.class, dataInserimento), dateCalendar.get(Calendar.YEAR)),
        cb.equal(cb.function("month", Integer.class, dataInserimento), dateCalendar.get(Calendar.MONTH) + 1),
        cb.equal(cb.function("day", Integer.class, dataInserimento), dateCalendar.get(Calendar.DATE)));

cq.where(..., timelessPredicate);
Run Code Online (Sandbox Code Playgroud)

我们在这里做了什么,我们分别利用hibernate函数和日历功能,将数据库中的年,月,日值与提供的输入日期进行比较.

这样就可以了.