休眠。优化sqlRestriction

时间:2013-03-12 14:06:08

标签: java mysql hibernate query-optimization

如何在没有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 
    }

在DB中我有这样的表示: date_column =&gt;日期时间(YYYY-MM-DD HH:mm:ss)。

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

1 个答案:

答案 0 :(得分:2)

是的,伙计:) 因此,如果您不想使用内置的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();
}