2010-04-08 69 views
4

目前我們的查詢添加了各種限制,以確保結果被視爲活動或活動。這些限制在幾個地方/查詢中使用這樣的方法是設置類似於休眠標準:爲標準和DetachedCriteria添加限制

public Criteria addStandardCriteria(Criteria criteria, ...) { 
     // Add restrictions, create aliases based on parameters 
     //  and other non-trivial logic 
    criteria.add(...); 
    return criteria; 
} 

這一直很好,到目前爲止,但需要被添加到使用的DetachedCriteria的子查詢現在這個標準規範。有沒有辦法修改這個方法來接受Criteria或DetachedCriteria或更好的方法來添加限制?

+0

你能給我多一點的信息? Criteria和DetachedCriteria都在它們上都有createCriteria()方法,所以你可以創建一個子標準,然後把它傳遞給這個方法。我不確定這是不是你問的問題。 – rancidfishbreath 2010-04-08 21:06:17

+0

我不認爲,因爲不是相同的,不擴展同一類。 – Gilean 2010-04-09 03:02:05

回答

1

我結束了重寫查詢,以便這不再是一個問題,但在此之前,我創建了這個類,這似乎工作,但您的里程可能會有所不同:

public class CriteriaContainer implements Serializable { 

    private static final long serialVersionUID = 1L; 

    private Criteria criteria = null; 
    private DetachedCriteria detachedCriteria = null; 

    public CriteriaContainer(Criteria criteria) { 
     this.criteria = criteria; 
     this.detachedCriteria = null; 
    } 

    public CriteriaContainer(DetachedCriteria detachedCriteria) { 
     this.detachedCriteria = detachedCriteria; 
     this.criteria = null; 
    } 

    /** 
    * @param eq 
    * @return 
    */ 
    public CriteriaContainer add(final Criterion eq) { 
     if (criteria != null) { 
      criteria.add(eq); 
     } else if (detachedCriteria != null) { 
      detachedCriteria.add(eq); 
     } 
     return this; 
    } 

    /** 
    * @return the criteria 
    */ 
    public Criteria getCriteria() { 
     return criteria; 
    } 

    /** 
    * @return the detachedCriteria 
    */ 
    public DetachedCriteria getDetachedCriteria() { 
     return detachedCriteria; 
    } 

    /** 
    * @param associationPath 
    * @param alias 
    * @return 
    */ 
    public CriteriaContainer createAlias(final String associationPath, final String alias) { 
     if (criteria != null) { 
      criteria.createAlias(associationPath, alias); 
     } else if (detachedCriteria != null) { 
      detachedCriteria.createAlias(associationPath, alias); 
     } 
     return this; 
    } 

    /** 
    * @param distinctRootEntity 
    * @return 
    */ 
    public CriteriaContainer setResultTransformer(final ResultTransformer transformer) { 
     if (criteria != null) { 
      criteria.setResultTransformer(transformer); 
     } else if (detachedCriteria != null) { 
      detachedCriteria.setResultTransformer(transformer); 
     } 
     return this; 
    } 
} 

criteria = addBasicCriteria(new CriteriaContainer(criteria), ...).getCriteria() 
detachedCriteria = addBasicCriteria(new CriteriaContainer(detachedCriteria), ...).getDetachedCriteria()