1

如何在没有 sqlRestriction 的情况下优化以下内容:

public List<SomeEntity> getEntityByYearMonthAndDay(Calendar cal) {
        Criteria criteria = helper.createCriteria();
        criteria.add(sqlRestriction("(DATE(date_column) = ?)", cal.getTime(), org.hibernate.type.StandardBasicTypes.DATE));
        return criteria.list();
}

SomeEntity 看起来像:

    @Entity
    @Table(name="some_table")
    public class SomeEntity extends Identifiable {


        @Column(name = "date_column")
        private Calendar dateColumn;

//Getters and setters 
    }

在数据库中,我有这样的表示:date_column => datetime (YYYY-MM-DD HH:mm:ss)。

很明显,逻辑只比较日期截断时间值。

4

1 回答 1

3

是的,伙计们 :) 所以如果你不想使用内置的 MySQL DATE(...) 函数而只使用 JPA:

public List<SomeEntity> getEntityByYearMonthAndDay(Calendar cal) {
    Criteria criteria = helper.createCriteria();
    Calendar leftBorder = Calendar.getInstance();
    leftBorder.setTime(cal.getTime());
    Calendar rightBorder = Calendar.getInstance();
    rightBorder.setTime(cal.getTime());
    rightBorder.add(Calendar.DATE, 1);
    Conjunction dateConjunction = Restrictions.conjunction();
    dateConjunction.add(Restrictions.eq("dateColumn", leftBorder));
    dateConjunction.add(Restrictions.lt("dateColumn", rightBorder));
    criteria.add(dateConjunction);
    return criteria.list();
}
于 2013-03-19T15:12:21.173 回答