1

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.

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.