如何将Hibernate“createAlias”子限制添加到父实体限制

时间:2014-03-04 04:46:27

标签: java hibernate hibernate-criteria

我有一个要求,我需要将搜索关键字应用于父实体(客户)的名称和状态,以及子实体订单的名称属性。

List<Criterion> aliasRestrictionsCriterion = new ArrayList<Criterion>();
Junction quotedLikeRestrictions = Restrictions.disjunction();
quotedLikeRestrictions.add(Restrictions.ilike("customerName", token, MatchMode.ANYWHERE));
quotedLikeRestrictions.add(Restrictions.ilike("customerState", token, MatchMode.ANYWHERE));
restrictions.add(quotedLikeRestrictions);

并在查询中包含子表我正在执行以下操作

Criteria alias = criteria.createAlias("order", "order")
.add(Restrictions.ilike("order.name", token, MatchMode.ANYWHERE));

Hibernate正在生成以下查询,但我需要的是将order.name(如compare)添加到父块中。

CUSTOMER this_ inner join ORDER order_ on this_.ORDER_ID=order_.ORDER_ID where 
(lcase(this_.name) like ? or lcase(this_.state) like ?) and (lcase(order_.NAME) 
like ?)        

我想要的是在父块中有(lcase(order_.NAME)像?)。所以我想要的是以下

(lcase(this_.name)喜欢?或lcase(this_.state)喜欢?或lcase(order_.NAME)之类的?)

我怎样才能做到这一点?

更新:这就是我调用标准的方式

protected List getEntities(List<Criterion> restrictions, String aliasSearchToken) {
    Session session = currentSession();
    Criteria criteria = session.createCriteria(getEntityClass());

    // apply restrictions.
    if (restrictions != null) {
        for (Criterion criterion : restrictions) {
            criteria.add(criterion);
        }
    }

    Criteria alias = criteria.createAlias("order", "order").add(Restrictions.ilike("order.name", searchToken, MatchMode.ANYWHERE));

    List list = criteria.list();
    if (list != null) {
        return list;
    }
    return Collections.emptyList();
}

更新2:

protected List getEntities(List<Criterion> restrictions, String aliasSearchToken) {
    Session session = currentSession();
    Criteria criteria = session.createCriteria(getEntityClass());

    Junction or = Restrictions.disjunction();
    or.add(Restrictions.ilike("order.name", searchToken, MatchMode.ANYWHERE));
    criteria.createAlias("order", "order").add(or);


    // apply restrictions.
    if (restrictions != null) {
        for (Criterion criterion : restrictions) {
            criteria.add(criterion);
        }
    }

    List list = criteria.list();
    if (list != null) {
        return list;
    }
    return Collections.emptyList();
}

产生     选择.......来自CUSTOMER this_ inner join ORDER order_ on this_.ORDER_ID = order_.uid where(lcase(order_.NAME)like?)和(lcase(this_.name)like?或lcase(this_.state) )喜欢?)

orderName就在之前,但仍然不在第二个或声明中......我很困惑。

1 个答案:

答案 0 :(得分:1)

好吧,您不必将限制添加到Criteria(创建AND),而是必须将其添加到quotedLikeRestrictions析取:

quotedLikeRestrictions.add(Restrictions.ilike("order.name", token, MatchMode.ANYWHERE));