开发者

How to specify Temporal type with JPA CriteriaBuilder?

I have a table that has a column with type of dateTime(I'm using SQL Server). I want to qu开发者_开发百科ery the table by the dateTime column. I want rows that have the same date or later in the dateTime column, but I want to give the date as a parameter. In short, dateTime must be greater or equal than a specified date.

The problem I have is that when I try to query with Date object using criteria API, it only gives rows from the next day. I'm suspecting that it tries to find find rows with the same millisecond or later. In JPA query language I can specify the Temporal type of the parameter(setParameter("dateColumn",myDate,Temporal.DATE)) but I can't find anything similar in the CriteriaBuilder API. Any suggestions?

My code looks currently like this:

cb.greaterThanOrEqualTo(r.<Date>get(fieldName), beginDate));


Since I haven't gotten an answer I'm going to assume there is now way to this other than programmatically in your application.

If I want to do a query for entities that were created after this weeks monday I have to create a Date object, set the date to monday and clear the hours, minutes, seconds and milliseconds from the Date object. Apache Commons Lang library has a helper class for just this situation called DateUtils. It has method truncate which can be used to get the unnecessary accuracy out of the Date object so you can use greatedThanOrEqual in CriteriaBuilder.


You can use ParameterExpression :

ParameterExpression<Calendar> beginDateParameter = cb.parameter(Calendar.class);
...
...
criteriaQuery.select(...)
  .where(criteriaBuilder.equal(r.get(fieldName), beginDateParameter));

entityManager.createQuery(criteriaQuery)
     .setParameter(beginDateParameter, beginDate, TemporalType.DATE)
     .getResultList(); 

Hibernate logs shows that date is passed as DateTime:

TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [0] as [DATE]


Well if I run the following class with DataNucleus JPA

@Entity
public class A
{
    @Id
    Long id;

    @Temporal(TemporalType.DATE)
    Date date;
}

this has the Date stored in a DATE column. And then run the following query

SELECT a FROM A a WHERE a.date >= :myDate"

passing in a java.util.Date as the parameter (including hour/min/second), it creates a query of

SELECT 'org.datanucleus.test.A' AS NUCLEUS_TYPE,A."DATE",A.ID,A."NAME" FROM A A WHERE A."DATE" >= <2009-06-15>

where the <2009-06-15> is a parameter to JDBC (the angle brackets are only shown to signify this), and I get no problems, i.e it correctly interprets the parameter as matching the type of what it compares against (which is what the JPA spec implies should happen)

Obviously if Hibernate has a problem with that you could pass in a java.sql.Date, and raise a bug on Hibernate

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜