简体   繁体   中英

Hibernate. Optimizing sqlRestriction

How can I optimize the following without 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 looks like:

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


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

//Getters and setters 
    }

In the DB I have such representation: date_column => datetime (YYYY-MM-DD HH:mm:ss).

It's obvious that logic compares only date truncating time values.

Yeah, guys :) So if you want not to use built-in MySQL DATE(...) function and use only 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM