2012-02-16 94 views
5

您無法在關聯上使用QBE令人非常沮喪。關聯關係的示例查詢

我有一個大約8個多對一列的數據表。每個列都有一個下拉列表來過濾表格。

假設如下:

表用戶

User { id, UserStatus, UserAuthorization } 

我想利用這個代碼:

User id=1 { UserStatus=Active, UserAuthorization=Admin } 

Criteria crit = getSession().createCriteria(class); 
crit.add(Example.create(userObject)); 

這並不在下面的例子中userObject工作

,因爲QBE不支持集合。要解決這個

一種方法是使用這種方式:

crit.createCriteria("UserStatus").add(Example.create(userStatusObject)); 
crit.createCriteria("UserAuthorization").add(Example.create(userAuthorizationObject)); 

我的問題是如何能夠動態地只用給定User對象進行編程。除了使用QBE還有其他方法嗎?

+0

用手工添加.add(Restriction.eq())? – Firo 2012-02-16 13:36:56

+0

我儘量避免...... QBE背後的要點是不要用手去做 – rotsch 2012-02-16 15:47:00

+0

我只是回答「有沒有比使用QBE還有其他方法?」 :D – Firo 2012-02-16 16:13:48

回答

2

你可以結合QBE和正常表達式來處理部分QBE犯規支持

Criteria crit = getSession().createCriteria(class); 
    .add(Example.create(userObject)); 
    .add(Expression.eq("UserStatus", userObject.getUserStatus())); 
+0

謝謝,有什麼辦法可以使這種動態? – rotsch 2012-02-17 06:42:35

1

這裏是我的倉庫基地,我發現爲我工作裏面一個通用的答案,使用反射:

protected T GetByExample(T example) 
{ 
    var c = DetachedCriteria.For<T>().Add(Example.Create(example).ExcludeNone()); 
    var props = typeof (T).GetProperties() 
     .Where(p => p.PropertyType.GetInterfaces().Contains(typeof(IEntityBase))); 
    foreach (var pInfo in props) 
    { 
     c.Add(Restrictions.Eq(pInfo.Name, pInfo.GetValue(example))); 
    } 
    return Query(c); 
} 

請注意,我的所有實體都繼承自IEntityBase,它允許我只從對象屬性中找到那些外鍵引用,以便將它們添加到條件中。您需要提供某種方式來執行查詢(即c.GetExecutableCriteria(Session))

0

以下是可供每個實體使用查詢的示例在hibernate中使用的代碼。

/** 
       * This method will use for query by example with association 
       * @param exampleInstance the persistent class(T) object 
       * @param restrictPropertyName the string object contains the field name of the association 
       * @param restrictPropertyValue the association object 
       * @return list the persistent class list 
       */ 
public List<T> queryByExampleWithRestriction(T exampleInstance, String restrictPropertyName, Object restrictPropertyValue) { 
      log.info("Inside queryByExampleWithRestriction method of GenericHibernateDAO"); 
      List<T> list = null; 
      try { 
       Criteria criteria = getSession().createCriteria(exampleInstance.getClass()); 
       Example example = Example.create(exampleInstance); 
       criteria.add(example); 
       criteria.add(Restrictions.eq(restrictPropertyName, restrictPropertyValue)); 
       list = criteria.list(); 
       log.info("Executed the queryByExampleWithRestriction query with criteria successfully!"); 
      } catch(HibernateException e){ 
       throw (e); 
      } 
      finally{ 
       this.closeSession(); 
      } 
      return list; 
     }