hibernate条件搜索多个实体

时间:2011-11-09 23:42:50

标签: java hibernate hibernate-criteria

我有三个实体:Log,Employee和Agency

记录与员工的多对一关联

与代理商有多对一关联的员工

DetachedCriteria criteria = DetachedCriteria.forClass(Log.class);

if (StringUtils.isNotBlank(c.getName())) {
      criteria.createAlias("employee", "e").add(Restrictions.ilike("e.name", "%" + c.getName() + "%"));
    }
if (StringUtils.isNotBlank(c.getAgency())) {
      criteria.createAlias("employee", "e").createAlias("agency", "a").add(Restrictions.ilike("e.a.name", "%" + c.getAgency() + "%"));
        }

上述内容适用于员工姓名,但不适用于代理商名称。

我收到以下错误:

Exception: org.hibernate.QueryException: could not resolve property: agency of: com.example.Log

我发现的所有例子都只降低了一级。有人能指出我的资源,告诉我如何导航下来吗?

2 个答案:

答案 0 :(得分:3)

尝试以下代码

DetachedCriteria criteria = DetachedCriteria.forClass(Log.class);
criteria.createAlias("employee", "e");

if (StringUtils.isNotBlank(c.getName())) {
    criteria.add(Restrictions.ilike("e.name", c.getName(), MatchMode.ANYWHERE));
}

if (StringUtils.isNotBlank(c.getAgency())) {
    criteria.createAlias("e.agency", "a"); //  <===========
    criteria.add(Restrictions.ilike("a.name", c.getAgency(), MatchMode.ANYWHERE));
}

答案 1 :(得分:3)

第二个应该像这样工作:

criteria.createAlias("employee", "e").createAlias("e.agency","a")
           .add(Restrictions.ilike("a.name", "%" + c.getAgency() + "%"));