2012-02-16 4 views
5

アソシエーション上でQBEを使用できないことは非常に不快です。アソシエーションの例による照会

私は約8個の多対1の列で大きなデータテーブルを持っています。テーブルをフィルタリングするためのすべての列のドロップダウンリストがあります。

のは、次のことを想定してみましょう:

テーブルユーザー

User { id, UserStatus, UserAuthorization } 

私はこのコードを使用する:

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

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

これは、次の例userObject上では動作しません。

QBEはコレクションをサポートしていないためです。

これを解決する1つの方法は、このようにそれを使用することです。

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

私の質問は、これは単に与えられたUserオブジェクトを動的にプログラムすることができる方法です。 QBEを使用するよりも別の方法がありますか?

+0

.add(Restriction.eq())? – Firo

+0

私はそれを避けようとしています... QBEの背後にある全体のポイントは、手で何もしないことです。 – rotsch

+0

私はちょうど「QBEを使用するよりも別の方法がありますか? :D – Firo

答えて

2

あなたは部品QBE doesntのサポートを処理するために、QBE、通常の式を組み合わせることができます

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

ありがとう、このダイナミックを作る方法はありますか? – rotsch

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から継承しているので、オブジェクトのプロパティから外来キーの参照だけを見つけることができ、それを基準に追加することができました。

0

ここでは、クエリを使用するためにすべてのエンティティで使用できるコードを例でhibernateで使用しています(例:c.GetExecutableCriteria(Session))。

/** 
       * 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; 
     } 
関連する問題