2011-03-24 49 views
3

我需要使用標準來查詢數據庫。 我正在搜索的數據有一個日期,說'startDate',我有一個月說1月,我需要提取所有的數據,其中startDate月= 0;在SQL我會使用像'where month(startDate)= 0',但我不知道如何做到這一點與休眠標準,如果它是可能的。 你能幫我嗎? 謝謝你們。 盧卡。如何使用Hibernate條件在一個月查詢日期

回答

6

有了標準,我認爲你必須編寫自己的表達式類。像這樣的東西應該工作(沒有測試過,雖然):

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; 
    } 
} 

然後,你可以在一個標準中使用這個表達式:

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

它工作得很好,謝謝你,我無法想出了這樣一個解決方案,我覺得可憐。 – 2011-03-24 12:50:16

+2

@Luca Paoli:Hibernate是開源的。我只是查看了hibernate代碼中現有表達式的代碼。 – 2011-03-26 07:34:01

1

答案上面並沒有爲我工作,但與現在正在進行一些改變。

public class MonthEqExpression implements Criterion { 
    private final String propertyName; 
    private final Long month; 

    public MonthEqExpression(String propertyName, Long month) { 
     this.propertyName = propertyName; 
     this.month = month; 
    } 

    @Override 
    public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { 
     String[] columns = criteriaQuery.getColumns(propertyName, criteria); 
     if (columns.length != 1) { 
      throw new HibernateException("monthEq may only be used with single-column properties"); 
     } 
     return "extract(month from " + columns[0] + ") = ?"; 
    } 

    @Override 
    public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException { 
     return new TypedValue[] {new TypedValue(criteriaQuery.getIdentifierType(criteria), month, EntityMode.POJO)}; 
    } 

    @Override 
    public String toString() { 
     return "extract(month from " + propertyName + ") = " + month; 
    } 
} 

然後,你可以在一個標準中使用這個表達式:

criteria.add(new MonthEqExpression("startDate", new Long(1))); 
相關問題