第 16 章 条件查询(Criteria Queries) [url]http://oss.org.cn/ossdocs/framework/hibernate/reference-v3_zh-cn/querycriteria.html[/url]
hibernate存在如下表及关联:

class House{  
  private string houseid;  
  private string housename;  
}



class Shelf{  
  private string shelfid;  
  private House house;  
}



class Position{  
  private string positionid;  
  private Shelf shelf;  
}


class Warehouse{  
  private string warehouseid;  
  private Position position;  
}




Warehouse外键关联Pisition, Position外键关联Shelf, Shelf外键关联houseid。


现在要对Warehouse使用Criteria查询, 查询House的id,可使用如下方法:


Criteria criteria = BaseUtil.getCriteria(Warehouse.class);  
criteria.createAlias("position", "position");  
criteria.createAlias("position.shelf", "shelf");  
criteria.add(Expression.eq("shelf.house.houseid", "111"));




如果要查询House的name, 必须再关联House表:


Criteria criteria = BaseUtil.getCriteria(Warehouse.class);  
criteria.createAlias("position", "position");  
criteria.createAlias("position.shelf", "shelf");  
criteria.createAlias("shelf.house", "house");  
criteria.add(Expression.eq("house.housename", "name A"));




以上代码就可以实现了。



可是还会出现一个问题:如果表路径position已经被关联过了(比如此criteria是传入的参数,已经关联了Alias路径position, 并查询过了),则会报错。解决方法:


检查criteria里面关联的路径,如果已经关联,则不再关联,直接使用就行了。


class CriteriaUtil{  
public static Criteria addAlias(CriteriaImpl criteriaImpl, String path, String name){  
  if(path == null) return criteriaImpl;  
  for(Iterator iter = criteriaImpl.iterateSubcriteria();iter.hasNext();){  
    Subcriteria subCriteria = (Subcriteria)iter.next();  
    if(path.equals(subCriteria.getPath()))  
      return criteriaImpl;  
  }  
  return criteriaImpl.createAlias(path, name);  
}  
}




(注:这段代码有时是存在问题的,不是所有的Criteria 都能转换为CriteriaImpl,可能会是Subcriteria。因此,需要确保传入的参数为CriteriaImpl)



调用代码就变成:


Criteria criteria = BaseUtil.getCriteria(Warehouse.class);  
CriteriaUtil.addAlias((CriteriaImpl)criteria, "position", "position");  
CriteriaUtil.addAlias((CriteriaImpl)criteria, "position.shelf", "shelf");  
criteria.add(Expression.eq("shelf.house.houseid", "111"));