如何使用Hibernate条件查询一个月的日期 [英] How to query on a month for a date with Hibernate criteria
问题描述
我需要使用标准来查询数据库。
我正在搜索的数据有一个日期,比如'startDate',我有一个月的月份为1,我需要提取所有数据,其中startDate的月份为0;在SQL我会使用像'where month(startDate)= 0',但我不知道如何做到这一点与休眠标准,如果它是可能的。
你能帮我吗?
谢谢你们。
Luca。
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 startDate has month = 0; in sql I'd use something like 'where month(startDate) = 0' but I don't know how to do this with hibernate criteria and if it's possible at all. Can you help me? Thank you guys. Luca.
推荐答案
使用条件,我认为您必须编写自己的表达式类。这样的东西应该可以工作(虽然没有测试过):
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));
这篇关于如何使用Hibernate条件查询一个月的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!