2012-02-16 121 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; 
     }