Example usage for org.hibernate.criterion Restrictions or

List of usage examples for org.hibernate.criterion Restrictions or

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions or.

Prototype

public static LogicalExpression or(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the disjuction of two expressions

Usage

From source file:com.redhat.rhn.domain.channel.ChannelFamilyFactory.java

License:Open Source License

/**
 * Lookup the List of ChannelFamily objects that are labled starting
 * with the passed in label param//from  w ww  .j ava 2 s  .c om
 * @param label to query against
 * @param orgIn owning the Channel.  Pass in NULL if you want a NULL org channel
 * @return List of Channel objects
 */
public static List lookupByLabelLike(String label, Org orgIn) {
    Session session = getSession();
    Criteria c = session.createCriteria(ChannelFamily.class);
    c.add(Restrictions.like("label", label + "%"));
    c.add(Restrictions.or(Restrictions.eq("org", orgIn), Restrictions.isNull("org")));
    return c.list();
}

From source file:com.redhat.rhn.domain.common.ExceptionMessage.java

License:Open Source License

/**
 * Returns the exception message object associated to this id
 * @param exceptionId the exception id// w w w . j  ava  2s.  co  m
 * @return the associated exception object / null if not found otherwise
 */
public static ExceptionMessage lookup(long exceptionId) {
    Session session = HibernateFactory.getSession();
    Criteria criteria = session.createCriteria(ExceptionMessage.class);
    criteria.add(Restrictions.or(Restrictions.eq("id", -1 * exceptionId), Restrictions.eq("id", exceptionId)));
    return (ExceptionMessage) criteria.uniqueResult();
}

From source file:com.reignite.parser.QueryParser.java

License:Open Source License

private Criterion createOr(JSONArray ors, int index) throws ParserException {
    if (ors.length() == (index + 1)) {
        try {/*from  w  w w.j a va 2 s. co  m*/
            return createCriterion(ors.getJSONObject(index));
        } catch (JSONException e) {
            throw new ParserException(
                    "or clauses must be arrays with at least two elements: " + ors.toString());
        }
    }
    JSONObject orObj = null;
    try {
        orObj = ors.getJSONObject(index);
    } catch (JSONException e) {
        throw new ParserException("each element of an or clause must be a JSON Object. " + query.toString());
    }
    return Restrictions.or(createCriterion(orObj), createOr(ors, index + 1));
}

From source file:com.salesmanager.core.service.catalog.impl.db.dao.ProductDao.java

License:Open Source License

public SearchProductResponse searchProduct(SearchProductCriteria searchCriteria) {

    try {//from w ww  .j av a2s.c om

        Criteria criteria = super.getSession()
                .createCriteria(com.salesmanager.core.entity.catalog.Product.class)
                .add(Restrictions.eq("merchantId", searchCriteria.getMerchantId()));
        // .setFetchMode("descriptions", FetchMode.JOIN);

        // select p from Product p left join fetch p.descriptions s left
        // join fetch p.specials y left join fetch p.prices r left join
        // fetch r.priceDescriptions rd left join fetch r.special x where
        // p.merchantId=:mId and p.masterCategoryId in(:cId) and
        // s.id.languageId=:lId order by p.productSortOrder
        StringBuffer q = new StringBuffer();
        q.append(
                "select p from Product p left join fetch p.descriptions s left join fetch p.specials y left join fetch p.prices r left join fetch r.priceDescriptions rd left join fetch r.special x where p.merchantId=:mId and s.id.languageId=:lId");

        List inlist = null;
        if (searchCriteria.getCategoryid() != -1) {

            // only products in categories
            CatalogService cservice = (CatalogService) ServiceFactory.getService(ServiceFactory.CatalogService);
            Map categories = cservice.getCategoriesByLang(searchCriteria.getMerchantId(),
                    LanguageUtil.getLanguageStringCode(searchCriteria.getLanguageId()));
            Category c = (Category) categories.get(searchCriteria.getCategoryid());
            // StringBuffer inlist = null;
            // if(c.getParentId()==0) {
            // List subcategs =
            // cservice.getCategoriesIdPerSubCategories(LanguageUtil.getLanguageStringCode(searchCriteria.getLanguageId()),c);
            List subcategs = cservice.findSubCategories(c.getCategoryId());
            if (subcategs != null && subcategs.size() > 0) {
                inlist = new ArrayList();
                inlist.add(searchCriteria.getCategoryid());
                Iterator it = subcategs.iterator();
                while (it.hasNext()) {
                    Category category = (Category) it.next();
                    long cid = category.getCategoryId();
                    inlist.add(cid);
                }
            }
            // }
        }

        if (searchCriteria != null) {

            if (inlist != null) {
                q.append(" and p.masterCategoryId in(:mcIds)");
            } else if (searchCriteria.getCategoryid() != -1 && inlist == null) {
                q.append(" and p.masterCategoryId = :mcId");
            }

            if (searchCriteria.getVisible() != SearchProductCriteria.VISIBLEALL) {// visibility

                if (searchCriteria.getVisible() == SearchProductCriteria.VISIBLETRUE) {

                    q.append(" and p.productDateAvailable <= :dt");

                } else {

                    q.append(" and p.productDateAvailable > :dt");

                }
            }
            if (searchCriteria.getStatus() != SearchProductCriteria.STATUSALL) {// availability

                q.append(" and p.productStatus = :st");
            }
            if (!StringUtils.isBlank(searchCriteria.getDescription())) {

                q.append(" and s.productName like :pName");
                // q.append(" and s.productName like '%lounge%'");

            }

        }

        /*
         * Criteria query = super.getSession()
         * .createCriteria(com.salesmanager
         * .core.entity.catalog.Product.class)
         * .add(Restrictions.eq("merchantId",
         * searchCriteria.getMerchantId())) //.setFetchMode("descriptions",
         * FetchMode.JOIN)
         * .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
         */

        Query c = super.getSession().createQuery(q.toString());
        c.setInteger("mId", searchCriteria.getMerchantId());
        c.setInteger("lId", searchCriteria.getLanguageId());

        /*
         * Criteria descCriteria = criteria.createCriteria("descriptions")
         * .add(Restrictions.eq("id.languageId",
         * searchCriteria.getLanguageId()));
         * 
         * Criteria descCriteriaQ = query.createCriteria("descriptions")
         * .add(Restrictions.eq("id.languageId",
         * searchCriteria.getLanguageId()));
         */

        if (searchCriteria != null) {

            if (inlist != null) {

                criteria.add(Restrictions.in("masterCategoryId", inlist));
                // query.add(Restrictions.in("masterCategoryId", inlist));
                c.setParameterList("mcIds", inlist);

            } else if (searchCriteria.getCategoryid() != -1 && inlist == null) {

                criteria.add(Restrictions.eq("masterCategoryId", searchCriteria.getCategoryid()));
                // query.add(Restrictions.eq("masterCategoryId",
                // searchCriteria.getCategoryid()));
                c.setLong("mcId", searchCriteria.getCategoryid());

                // wherecategory =
                // " and products_view.master_categories_id IN " +
                // inlist.toString();
            }

        }

        if (searchCriteria.getVisible() != SearchProductCriteria.VISIBLEALL) {// visibility

            if (searchCriteria.getVisible() == SearchProductCriteria.VISIBLETRUE) {
                // wherevisible =
                // " and products_view.products_date_available IS NOT NULL and products_view.products_date_available < now()";

                criteria.add(Expression.isNotNull("productDateAvailable"));
                criteria.add(Expression.lt("productDateAvailable",
                        new java.util.Date(new java.util.Date().getTime())));
                // query.add(Expression.isNotNull("productDateAvailable"));
                // query.add(Expression.lt("productDateAvailable",new
                // java.util.Date(new java.util.Date().getTime())));

                c.setParameter("dt", new Date());

            } else {
                // wherevisible =
                // " and (products_view.products_date_available IS NULL or products_view.products_date_available > now())";
                criteria.add(Restrictions.or(Expression.isNull("productDateAvailable"), Expression
                        .gt("productDateAvailable", new java.util.Date(new java.util.Date().getTime()))));
                // query.add(Restrictions.or(Expression.isNull("productDateAvailable"),Expression.gt("productDateAvailable",new
                // java.util.Date(new java.util.Date().getTime()))));

                c.setParameter("dt", new Date());

            }
        }
        if (searchCriteria.getStatus() != SearchProductCriteria.STATUSALL) {// availability
            criteria.add(Restrictions.eq("productStatus",
                    searchCriteria.getStatus() == SearchProductCriteria.STATUSINSTOCK ? new Boolean("true")
                            : new Boolean("false")));
            // query.add(Restrictions.eq("productStatus",
            // searchCriteria.getStatus()==SearchProductCriteria.STATUSINSTOCK?new
            // Boolean("true"):new Boolean("false")));
            // wherestatus = " and products_view.products_status=" +
            // criteria.getStatus();
            c.setBoolean("st",
                    searchCriteria.getStatus() == SearchProductCriteria.STATUSINSTOCK ? new Boolean("true")
                            : new Boolean("false"));
        }
        if (!StringUtils.isBlank(searchCriteria.getDescription())) {
            criteria.createAlias("descriptions", "description")
                    .add(Restrictions.eq("description.id.languageId", searchCriteria.getLanguageId()))
                    .add(Restrictions.like("description.productName",
                            "%" + searchCriteria.getDescription() + "%"));
            // query.createAlias("descriptions",
            // "description").add(Restrictions.eq("description.id.languageId",
            // searchCriteria.getLanguageId())).add(Restrictions.like("description.productName",
            // "%"+searchCriteria.getDescription()+"%"));
            // descCriteria.add((Restrictions.like("productName",
            // "%"+searchCriteria.getDescription()+"%")));
            // descCriteriaQ.add((Restrictions.like("productName",
            // "%"+searchCriteria.getDescription()+"%")));
            // wherename = " and products_description.products_name LIKE '%"
            // + criteria.getName() + "%'";
            c.setString("pName", "%" + searchCriteria.getDescription() + "%");

        }

        criteria.setProjection(Projections.rowCount());
        Integer count = (Integer) criteria.uniqueResult();

        criteria.setProjection(null);

        int max = searchCriteria.getQuantity();

        /*
         * List list = query
         * .setMaxResults(searchCriteria.getUpperLimit(count))
         * .setFirstResult(searchCriteria.getLowerLimit()).list();
         */

        List list = null;
        // .setMaxResults(searchCriteria.getUpperLimit(count))
        // .setFirstResult(searchCriteria.getLowerLimit()).list();

        if (max != -1 && count > 0) {
            c.setMaxResults(searchCriteria.getUpperLimit(count));
            c.setFirstResult(searchCriteria.getLowerLimit());
            list = c.list();
        } else {
            list = c.list();
        }

        /*
         * //set short name if(list != null) { Iterator i = list.iterator();
         * while(i.hasNext()) { com.salesmanager.core.entity.catalog.Product
         * v = (com.salesmanager.core.entity.catalog.Product)i.next();
         * v.setName(v.getDescription()); Set descs = v.getDescriptions();
         * String shortName = ""; if(descs!=null) { Iterator di =
         * descs.iterator(); while(di.hasNext()) { ProductDescription pd =
         * (ProductDescription)di.next(); ProductDescriptionId id =
         * pd.getId();
         * if(id.getLanguageId()==searchCriteria.getLanguageId()) {
         * shortName = pd.getProductName(); break; } } }
         * v.setName(shortName); } }
         */

        SearchProductResponse response = new SearchProductResponse();
        response.setCount(count);

        response.setProducts(list);

        return response;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.sam.moca.job.dao.hibernate.JobDefinitionHibernateDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//w w  w .  j  a v  a2s .  c o  m
public List<JobDefinition> readForAllAndRoles(RoleDefinition... roles) {
    Criteria criteria = HibernateTools.getSession().createCriteria(JobDefinition.class);

    Criterion criterion = Restrictions.sqlRestriction("{alias}.role_id = '*'");

    if (roles.length > 0) {

        criterion = Restrictions.or(criterion, Restrictions.in("role", roles));
    }

    criteria.add(criterion);
    return (List<JobDefinition>) criteria.list();
}

From source file:com.sam.moca.task.dao.hibernate.TaskDefinitionHibernateDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from  www . ja  va  2  s  .c o m
public List<TaskDefinition> readAllTasksForAllAndRoles(RoleDefinition... roles) {
    Criteria criteria = HibernateTools.getSession().createCriteria(TaskDefinition.class);

    Criterion criterion = Restrictions.sqlRestriction("{alias}.role_id = '*'");

    if (roles.length > 0) {
        Object[] values = new Object[roles.length];
        Type[] types = new Type[roles.length];
        StringBuilder builder = new StringBuilder("{alias}.task_id in (");

        for (int i = 0; i < roles.length; ++i) {
            if (i != 0) {
                builder.append(", ");
            }
            builder.append('?');
            values[i] = roles[i].getRoleId();
            types[i] = StandardBasicTypes.STRING;
        }

        builder.append(')');

        LogicalExpression expr = Restrictions.or(Restrictions.sqlRestriction(builder.toString(), values, types),
                Restrictions.in("role", roles));
        criterion = Restrictions.or(criterion, expr);
    }

    criteria.add(criterion);
    return (List<TaskDefinition>) criteria.list();
}

From source file:com.sapienter.jbilling.server.order.db.OrderDAS.java

License:Open Source License

/**
 * @author othman/*w ww.  j  av  a2  s . com*/
 * @return list of active orders
 */
public List<OrderDTO> findToActivateOrders() {
    Date today = Util.truncateDate(new Date());
    Criteria criteria = getSession().createCriteria(OrderDTO.class);

    criteria.add(Restrictions.eq("deleted", 0));
    criteria.add(Restrictions.or(Expression.le("activeSince", today), Expression.isNull("activeSince")));
    criteria.add(Restrictions.or(Expression.gt("activeUntil", today), Expression.isNull("activeUntil")));

    return criteria.list();
}

From source file:com.sapienter.jbilling.server.order.db.OrderDAS.java

License:Open Source License

/**
 * @author othman/*from w ww . ja v a  2 s  .  c  o m*/
 * @return list of inactive orders
 */
public List<OrderDTO> findToDeActiveOrders() {
    Date today = Util.truncateDate(new Date());
    Criteria criteria = getSession().createCriteria(OrderDTO.class);

    criteria.add(Restrictions.eq("deleted", 0));
    criteria.add(Restrictions.or(Expression.gt("activeSince", today), Expression.le("activeUntil", today)));

    return criteria.list();
}

From source file:com.sccl.attech.modules.sys.service.LogService.java

License:Open Source License

public Page<Log> find(Page<Log> page, Map<String, Object> paramMap) {
    DetachedCriteria dc = logDao.createDetachedCriteria();

    //      Long createById = StringUtils.toLong(paramMap.get("createById"));
    //      if (createById > 0){
    //         dc.add(Restrictions.eq("createBy.id", createById));
    //      }/* w  w w .j a  va 2s . c  om*/
    String type = ObjectUtils.toString(paramMap.get("type"));
    if ("0".equals(type)) {//???
        dc.add(Restrictions.eq("type", type));
    } else {
        String manageName = ObjectUtils.toString(paramMap.get("manageName"));
        if (StringUtils.isNotBlank(manageName)) {
            dc.createAlias("createBy", "createBy");
            dc.add(Restrictions.like("createBy.name", "%" + EncodedUtil.decodeValue(manageName) + "%"));
        }
        dc.createAlias("company", "company");
        String companyId = ObjectUtils.toString(paramMap.get("companyId"));
        if (StringUtils.isNotBlank(companyId)) {

            dc.add(Restrictions.eq("company.id", companyId));
        }

        String requestUri = ObjectUtils.toString(paramMap.get("requestUri"));
        if (StringUtils.isNotBlank(requestUri)) {
            dc.add(Restrictions.like("requestUri", "%" + requestUri + "%"));
        }

        String exception = ObjectUtils.toString(paramMap.get("exception"));
        if (StringUtils.isNotBlank(exception)) {
            dc.add(Restrictions.eq("type", Log.TYPE_EXCEPTION));
        }

        if (StringUtils.isNotBlank(type)) {
            dc.add(Restrictions.eq("type", type));
        }

        Date beginDate = DateUtils.parseDate(paramMap.get("start"));
        if (beginDate == null) {
            beginDate = DateUtils.setDays(new Date(), 1);
            paramMap.put("beginDate", DateUtils.formatDate(beginDate, "yyyy-MM-dd"));
        }
        Date endDate = DateUtils.parseDate(paramMap.get("end"));
        if (endDate == null) {
            endDate = DateUtils.addDays(DateUtils.addMonths(beginDate, 1), -1);
            paramMap.put("endDate", DateUtils.formatDate(endDate, "yyyy-MM-dd"));
        }
        dc.createAlias("office", "office");
        User currentUser = UserUtils.getUser();
        dc.add(Restrictions.or(dataScopeFilter(currentUser, "office", "createBy"),
                Restrictions.eq("type", "0")));
        dc.add(Restrictions.between("createDate", beginDate, endDate));
    }
    dc.addOrder(Order.desc("createDate"));
    return logDao.find(page, dc);
}

From source file:com.sccl.attech.modules.sys.service.SystemService.java

License:Open Source License

/**
 * ?/*from  w w w.j  ava2 s .  c  o m*/
 * @param user
 * @return
 */
public List<User> getList(User user) {
    User currentUser = UserUtils.getUser();
    DetachedCriteria dc = userDao.createDetachedCriteria();

    dc.createAlias("company", "company");
    if (user.getCompany() != null && StringUtils.isNotBlank(user.getCompany().getId())) {
        dc.add(Restrictions.or(Restrictions.eq("company.id", user.getCompany().getId()),
                Restrictions.like("company.parentIds", "%," + user.getCompany().getId() + ",%")));
    }

    dc.createAlias("office", "office");
    if (user.getOffice() != null && StringUtils.isNotBlank(user.getOffice().getId())) {
        dc.add(Restrictions.or(Restrictions.eq("office.id", user.getOffice().getId()),
                Restrictions.like("office.parentIds", "%," + user.getOffice().getId() + ",%")));
    }

    // ????
    if (!currentUser.isAdmin()) {
        dc.add(Restrictions.ne("id", "1"));
    }
    if (user.getUserType() != null && !"".equals(user.getUserType())) {
        dc.add(Restrictions.eq("userType", user.getUserType()));
    }

    dc.add(dataScopeFilter(currentUser, "office", ""));

    if (StringUtils.isNotEmpty(user.getLoginName())) {
        dc.add(Restrictions.like("loginName", "%" + user.getLoginName() + "%"));
    }
    if (StringUtils.isNotEmpty(user.getName())) {
        String userName = EncodedUtil.decodeValue(user.getName());
        dc.add(Restrictions.like("name", "%" + userName + "%"));
    }
    if (StringUtils.isNotEmpty(user.getUserType())) {
        dc.add(Restrictions.eq("userType", user.getUserType()));
    }

    dc.add(Restrictions.eq(User.FIELD_DEL_FLAG, User.DEL_FLAG_NORMAL));

    return userDao.find(dc);

}