How to query on a month for a date with Hibernate criteria

后端 未结 2 607
难免孤独
难免孤独 2020-12-18 09:56

I need to use criteria to query a database. The data I\'m searching has a date, say \'startDate\' and I have a month say 0 for January, I need to extract all data where star

2条回答
  •  难免孤独
    2020-12-18 10:28

    With criteria, I think you'll have to write your own expression class. Something like this should work (not tested, though):

    public class MonthEqExpression implements Criterion {
    
        private final String propertyName;
        private final int month;
    
        public MonthEqExpression(String propertyName, int month) {
            this.propertyName = propertyName;
            this.month = month;
        }
    
        @Override
        public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery)
            throws HibernateException {
                String[] columns = criteriaQuery.findColumns(propertyName, criteria);
                if (columns.length!=1) {
                    throw new HibernateException("monthEq may only be used with single-column properties");
                }
                return "month(" + columns[0] + ") = ?";
            }
    
        @Override
        public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
            return new TypedValue[] {new TypedValue(IntegerType.INSTANCE, month, EntityMode.POJO)};
        }
    
        @Override
        public String toString() {
            return "month(" + propertyName + ") = " + month;
        }
    }
    

    And then, you can use this expression in a criteria:

    criteria.add(new MonthEqExpression("startDate", 0));
    

提交回复
热议问题