Example usage for org.hibernate.criterion Restrictions in

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

Introduction

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

Prototype

public static Criterion in(String propertyName, Collection values) 

Source Link

Document

Apply an "in" constraint to the named property.

Usage

From source file:com.lushapp.modules.sys.web.AviationOrderController.java

License:Apache License

/**
 * combogrid//www .  j  a  va 2s  .  c o m
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "combogrid" })
@ResponseBody
public Datagrid<AviationOrder> combogrid(@RequestParam(value = "ids", required = false) List<Long> ids,
        String loginNameOrName, Integer rows) throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
        //in?
        Criterion inCriterion = Restrictions.in("id", ids);

        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
            criterion = Restrictions.or(inCriterion, criterion1);
        } else {
            criterion = inCriterion;
        }
        //??
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
    } else {
        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            criterion = Restrictions.or(loginNameCriterion, nameCriterion);
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        }
    }

    //
    Page<AviationOrder> p = new Page<AviationOrder>(rows);//
    p = aviationOrderManager.findByCriteria(p, criterions);
    Datagrid<AviationOrder> dg = new Datagrid<AviationOrder>(p.getTotalCount(), p.getResult());
    return dg;
}

From source file:com.lushapp.modules.sys.web.AviationSuppliersController.java

License:Apache License

/**
 * combogrid/*from w  w w .  j  a  va2  s. c  o  m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "combogrid" })
@ResponseBody
public Datagrid<AviationSuppliers> combogrid(@RequestParam(value = "ids", required = false) List<Long> ids,
        String loginNameOrName, Integer rows) throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
        //in?
        Criterion inCriterion = Restrictions.in("id", ids);

        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
            criterion = Restrictions.or(inCriterion, criterion1);
        } else {
            criterion = inCriterion;
        }
        //??
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
    } else {
        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            criterion = Restrictions.or(loginNameCriterion, nameCriterion);
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        }
    }

    //
    Page<AviationSuppliers> p = new Page<AviationSuppliers>(rows);//
    p = aviationSuppliersManager.findByCriteria(p, criterions);
    Datagrid<AviationSuppliers> dg = new Datagrid<AviationSuppliers>(p.getTotalCount(), p.getResult());
    return dg;
}

From source file:com.lushapp.modules.sys.web.OrganController.java

License:Apache License

/**
 * combogrid/*w  w  w  .j a  v  a2  s.  co m*/
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "combogrid" })
@ResponseBody
public Datagrid<Organ> combogrid(String nameOrCode,
        @RequestParam(value = "ids", required = false) List<Long> ids, Integer rows) throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
        //in?
        Criterion inCriterion = Restrictions.in("id", ids);

        if (StringUtils.isNotBlank(nameOrCode)) {
            Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
            Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
            Criterion criterion1 = Restrictions.or(nameCriterion, codeCriterion);
            criterion = Restrictions.or(inCriterion, criterion1);
        } else {
            criterion = inCriterion;
        }
        //??
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
    } else {
        if (StringUtils.isNotBlank(nameOrCode)) {
            Criterion nameCriterion = Restrictions.like("name", nameOrCode, MatchMode.ANYWHERE);
            Criterion codeCriterion = Restrictions.like("code", nameOrCode, MatchMode.ANYWHERE);
            criterion = Restrictions.or(nameCriterion, codeCriterion);
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        }
    }

    //
    Page<Organ> p = new Page<Organ>(rows);//
    p = organManager.findByCriteria(p, criterions);
    Datagrid<Organ> dg = new Datagrid<Organ>(p.getTotalCount(), p.getResult());
    return dg;
}

From source file:com.lushapp.modules.sys.web.UserController.java

License:Apache License

@RequestMapping(value = { "select" })
public String selectPage(String userIds, Model model) {
    List<User> users = Lists.newArrayList();
    if (StringUtils.isNotBlank(userIds)) {
        String[] userIdss = userIds.split(",");
        List<Long> userIdLs = Lists.newArrayList();
        for (String userId : userIdss) {
            userIdLs.add(Long.valueOf(userId));
        }/*from  ww  w. j a  va 2  s. co m*/
        Criterion inUserCriterion = Restrictions.in("id", userIdLs);
        users = userManager.findByCriteria(inUserCriterion);
    }
    model.addAttribute("users", users);

    return "modules/sys/user-select";
}

From source file:com.lushapp.modules.sys.web.UserController.java

License:Apache License

/**
 * combogrid// ww  w  .  j  av a2 s. c om
 *
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "combogrid" })
@ResponseBody
public Datagrid<User> combogrid(@RequestParam(value = "ids", required = false) List<Long> ids,
        String loginNameOrName, Integer rows) throws Exception {
    Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
    Criterion[] criterions = new Criterion[0];
    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
    Criterion criterion = null;
    if (Collections3.isNotEmpty(ids)) {
        //in?
        Criterion inCriterion = Restrictions.in("id", ids);

        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
            criterion = Restrictions.or(inCriterion, criterion1);
        } else {
            criterion = inCriterion;
        }
        //??
        criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
    } else {
        if (StringUtils.isNotBlank(loginNameOrName)) {
            Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName, MatchMode.ANYWHERE);
            Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
            criterion = Restrictions.or(loginNameCriterion, nameCriterion);
            //??
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
        }
    }

    //
    Page<User> p = new Page<User>(rows);//
    p = userManager.findByCriteria(p, criterions);
    Datagrid<User> dg = new Datagrid<User>(p.getTotalCount(), p.getResult());
    return dg;
}

From source file:com.mercatis.lighthouse3.persistence.events.hibernate.EventRegistryImplementation.java

License:Apache License

/**
 * This method generates criteria for a given event template that also
 * contain an ordering clause on the date of occurrence.
 * /*from   www. j a v a2 s. co  m*/
 * @param session
 *            the Hibernate session to use for criteria generation
 * @param entityTemplate
 *            the template for which to generate the criteria
 * @param descending
 *            <code>true</code> if descending order is wanted (the default)
 *            or <code>false</code> for ascending order.
 * @return
 */
public Criteria generateOrderingCriteria(Session session, Event entityTemplate, boolean descending) {
    Criteria criteria = super.entityToCriteria(session, entityTemplate);

    if (entityTemplate.getContext() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getContext()))
            criteria.add(Restrictions.eq("context", entityTemplate.getContext()));
        else
            criteria.add(Restrictions.in("context",
                    Ranger.castToEnumerationRange(entityTemplate.getContext()).getEnumeration()));

    }

    if (entityTemplate.getCode() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getCode()))
            criteria.add(Restrictions.eq("code", entityTemplate.getCode()));
        else
            criteria.add(Restrictions.in("code",
                    Ranger.castToEnumerationRange(entityTemplate.getCode()).getEnumeration()));

    }

    if (entityTemplate.getLevel() != null) {
        if (!Ranger.isEnumerationRange(entityTemplate.getLevel()))
            criteria.add(Restrictions.eq("level", entityTemplate.getLevel()));
        else
            criteria.add(Restrictions.in("level",
                    Ranger.castToEnumerationRange(entityTemplate.getLevel()).getEnumeration()));
    }

    if (entityTemplate.getMachineOfOrigin() != null)
        criteria.add(Restrictions.eq("machineOfOrigin", entityTemplate.getMachineOfOrigin()));

    if (entityTemplate.getMessage() != null) {
        criteria.add(Restrictions.ilike("message", "%" + entityTemplate.getMessage() + "%"));
    }

    if (entityTemplate.getStackTrace() != null) {
        if (this.unitOfWork.getSqlDialect() instanceof org.hibernate.dialect.MySQL5InnoDBDialect)
            criteria.add(Restrictions.sqlRestriction("match ({alias}.STACK_TRACE) against (?)",
                    entityTemplate.getStackTrace(), StringType.INSTANCE));
        else
            criteria.add(Restrictions.ilike("stackTrace", "%" + entityTemplate.getStackTrace() + "%"));
    }

    if (entityTemplate.getDateOfOccurrence() != null) {
        if (!Ranger.isIntervalRange(entityTemplate.getDateOfOccurrence())) {
            criteria.add(Restrictions.eq("dateOfOccurrence", entityTemplate.getDateOfOccurrence()));
        } else {
            Date lowerBound = Ranger.castToIntervalRange(entityTemplate.getDateOfOccurrence()).getLowerBound();
            Date upperBound = Ranger.castToIntervalRange(entityTemplate.getDateOfOccurrence()).getUpperBound();

            if ((lowerBound == null) && (upperBound != null))
                criteria.add(Restrictions.le("dateOfOccurrence", upperBound));
            else if ((lowerBound != null) && (upperBound == null))
                criteria.add(Restrictions.ge("dateOfOccurrence", lowerBound));
            else if ((lowerBound != null) && (upperBound != null)) {
                criteria.add(Restrictions.le("dateOfOccurrence", upperBound));
                criteria.add(Restrictions.ge("dateOfOccurrence", lowerBound));
            }
        }
    }

    if (!entityTemplate.getTransactionIds().isEmpty()) {
        Set<Criterion> transactionRestrictions = new HashSet<Criterion>();
        for (String transactionId : entityTemplate.getTransactionIds())
            transactionRestrictions.add(Restrictions.sqlRestriction(
                    "exists (select lti.* from EVENT_TRANSACTION_IDS lti where {alias}.EVT_ID = lti.EVT_ID and lti.TRANSACTION_ID = ?)",
                    transactionId, StringType.INSTANCE));

        if (transactionRestrictions.size() == 1) {
            criteria.add(transactionRestrictions.iterator().next());
        } else {
            Iterator<Criterion> restrictions = transactionRestrictions.iterator();
            Criterion orCriterion = restrictions.next();

            while (restrictions.hasNext()) {
                orCriterion = Restrictions.or(orCriterion, restrictions.next());
            }

            criteria.add(orCriterion);
        }
    }

    for (String tag : entityTemplate.getTags())
        criteria.add(Restrictions.sqlRestriction(
                "exists (select lt.* from EVENT_TAGS lt where {alias}.EVT_ID = lt.EVT_ID and lt.TAG = ?)", tag,
                StringType.INSTANCE));

    for (String udf : entityTemplate.getUdfs().keySet()) {
        Object value = entityTemplate.getUdf(udf);

        if (udf.equals("eventRESTResourceLimitRestriction")) {
            criteria.setMaxResults((Integer) value);
            break;
        }

        String columnName = "";
        Type valueType = StringType.INSTANCE;

        if (value instanceof Boolean) {
            columnName = "BOOLEAN_VAL";
            valueType = BooleanType.INSTANCE;
        }

        if (value instanceof Integer) {
            columnName = "INTEGER_VAL";
            valueType = IntegerType.INSTANCE;
        }

        if (value instanceof Long) {
            columnName = "LONG_VAL";
            valueType = LongType.INSTANCE;
        }

        if (value instanceof Float) {
            columnName = "FLOAT_VAL";
            valueType = FloatType.INSTANCE;
        }

        if (value instanceof Double) {
            columnName = "DOUBLE_VAL";
            valueType = DoubleType.INSTANCE;
        }

        if (value instanceof Date) {
            columnName = "DATE_VAL";
            valueType = DateType.INSTANCE;
        }

        if (value instanceof byte[]) {
            columnName = "BINARY_VAL";
            valueType = BlobType.INSTANCE;
        }

        if (value instanceof String) {
            columnName = "STRING_VAL";
            valueType = StringType.INSTANCE;
        }

        criteria.add(Restrictions.sqlRestriction(
                "exists (select lu.* from EVENT_UDFS lu where {alias}.EVT_ID = lu.EVT_ID and lu.UDF = ? and lu."
                        + columnName + " = ?)",
                new Object[] { udf, value }, new Type[] { StringType.INSTANCE, valueType }));

    }

    if (descending)
        criteria.addOrder(Order.desc("dateOfOccurrence"));
    else
        criteria.addOrder(Order.asc("dateOfOccurrence"));

    return criteria;
}

From source file:com.nec.harvest.service.impl.BudgetPerformanceServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override//from  ww w.ja va2 s.  co m
public Map<String, BudgetPerformance> findByOrgCodeAndMonthAndKmkCodeJs(String orgCode, String monthly,
        String... kmkCodeJs) throws ServiceException {
    if (StringUtils.isEmpty(orgCode)) {
        throw new IllegalArgumentException("Organization must not be null or empty");
    }
    if (StringUtils.isEmpty(monthly)) {
        throw new IllegalArgumentException("Monthly must not be null or empty");
    }
    if (ArrayUtils.isEmpty(kmkCodeJs)) {
        throw new IllegalArgumentException("KmkCodeJs must not be null");
    }

    final Session session = HibernateSessionManager.getSession();
    Transaction tx = null;

    Map<String, BudgetPerformance> mapBudgetPerformances = new HashMap<String, BudgetPerformance>();
    try {
        tx = session.beginTransaction();
        Criterion criterion = Restrictions.and(Restrictions.eq("pk.organization.strCode", orgCode),
                Restrictions.and(Restrictions.eq("pk.getSudo", monthly),
                        Restrictions.and(Restrictions.in("pk.kmkCodeJ", kmkCodeJs),
                                Restrictions.eq("delKbn", Constants.STATUS_ACTIVE))));
        Criteria crit = session.createCriteria(BudgetPerformance.class);
        crit.add(criterion);

        List<BudgetPerformance> budgetPerformances = repository.findByCriteria(crit);
        if (CollectionUtils.isNotEmpty(budgetPerformances)) {
            for (int i = 0; i < budgetPerformances.size(); i++) {
                BudgetPerformance budgetPerformance = budgetPerformances.get(i);
                mapBudgetPerformances.put(budgetPerformance.getPk().getKmkCodeJ(), budgetPerformance);
            }
        }
        tx.commit();
    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw new ServiceException(
                "An exception occured while get budget performance data by organization code " + orgCode, ex);
    } finally {
        HibernateSessionManager.closeSession(session);
    }
    return mapBudgetPerformances;
}

From source file:com.nec.harvest.service.impl.BudgetPerformanceServiceImpl.java

License:Open Source License

/** {@inheritDoc} */
@Override/*from  w w w .j  a  va  2s.c om*/
public Map<String, BudgetPerformance> findByOrgCodeAndStartMonthEndMonthAndKmkCodeJs(String orgCode,
        String startMonth, String endMonth, String... kmkCodeJs) throws ServiceException {
    if (StringUtils.isEmpty(orgCode)) {
        throw new IllegalArgumentException(
                "Organization code or current month in acton must not be null or empty");
    }
    if (StringUtils.isEmpty(startMonth)) {
        throw new IllegalArgumentException("Start month must not be null or empty");
    }
    if (StringUtils.isEmpty(endMonth)) {
        throw new IllegalArgumentException("End month month must not be null or empty");
    }
    if (ArrayUtils.isEmpty(kmkCodeJs)) {
        throw new IllegalArgumentException("KmkCodeJs must not be null");
    }

    // 
    logger.info("Find by organization code:" + orgCode + " startMonth " + startMonth + " endMonth " + endMonth
            + "kmkcodej " + StringUtils.join(kmkCodeJs, ","));
    final Session session = HibernateSessionManager.getSession();
    Transaction tx = null;

    Map<String, BudgetPerformance> mapBudgetPerformances = new HashMap<String, BudgetPerformance>();

    try {
        tx = session.beginTransaction();
        Criterion criterion = Restrictions.and(Restrictions.eq("pk.organization.strCode", orgCode),
                Restrictions.and(Restrictions.ge("pk.getSudo", startMonth),
                        Restrictions.and(Restrictions.le("pk.getSudo", endMonth),
                                Restrictions.and(Restrictions.in("pk.kmkCodeJ", kmkCodeJs),
                                        Restrictions.eq("delKbn", Constants.STATUS_ACTIVE)))));
        Criteria crit = session.createCriteria(BudgetPerformance.class);
        crit.add(criterion);

        List<BudgetPerformance> budgetPerformances = repository.findByCriteria(crit);
        // Release transaction
        tx.commit();
        if (CollectionUtils.isEmpty(budgetPerformances)) {
            throw new ObjectNotFoundException("There is no the budget performance object");
        }

        mapBudgetPerformances = new HashMap<String, BudgetPerformance>();
        for (BudgetPerformance budgetPerformance : budgetPerformances) {
            mapBudgetPerformances.put(
                    budgetPerformance.getPk().getGetSudo() + budgetPerformance.getPk().getKmkCodeJ(),
                    budgetPerformance);
        }
    } catch (HibernateException ex) {
        if (tx != null) {
            tx.rollback();
        }
        throw new ServiceException(
                "An exception occured while get budget performance data by organization code " + orgCode, ex);
    } finally {
        HibernateSessionManager.closeSession(session);
    }
    return mapBudgetPerformances;
}

From source file:com.photon.phresco.eshop.service.EShopService.java

License:Apache License

public List<ProductHBM> getProducts(final int categoryId) throws EShopException {
    @SuppressWarnings("unchecked")
    List<ProductHBM> productList = (List<ProductHBM>) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            DetachedCriteria criteria = DetachedCriteria.forClass(ProductHBM.class)
                    .add(Restrictions.eq("categoryId", categoryId));

            List<ProductHBM> productHBMs = template.findByCriteria(criteria);
            List<ProductHBM> productHBMList = new ArrayList<ProductHBM>(10);

            for (ProductHBM productHBM : productHBMs) {
                Object[] values = { 1, 2, 3, 4, 5 };
                List<ReviewHBM> reviewHBMs = session.createCriteria(ReviewHBM.class)
                        .add(Restrictions.in("ratings", values))
                        .add(Restrictions.eq("productId", productHBM.getProductId())).list();

                int rating = 0;

                // TODO average rating calculation not working
                if (reviewHBMs != null && reviewHBMs.size() > 0) {
                    ReviewHBM reviewHBM = reviewHBMs.get(0);
                    rating = ServiceUtil.getRating(reviewHBM.getRatings());
                }/*from   w  ww .j  av a 2s .c o  m*/

                productHBM.setRating(rating);
                productHBMList.add(productHBM);
            }

            return productHBMList;
        }
    });

    return productList;
}

From source file:com.photon.phresco.eshop.service.EShopService.java

License:Apache License

public List<ProductHBM> getProducts() throws EShopException {
    @SuppressWarnings("unchecked")
    List<ProductHBM> productList = (List<ProductHBM>) template.execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            DetachedCriteria criteria = DetachedCriteria.forClass(ProductHBM.class);

            List<ProductHBM> productHBMs = template.findByCriteria(criteria);
            List<ProductHBM> productHBMList = new ArrayList<ProductHBM>(100);

            for (ProductHBM productHBM : productHBMs) {
                Object[] values = { 1, 2, 3, 4, 5 };
                List<ReviewHBM> reviewHBMs = session.createCriteria(ReviewHBM.class)
                        .add(Restrictions.in("ratings", values))
                        .add(Restrictions.eq("productId", productHBM.getProductId())).list();
                int rating = 0;

                // TODO average rating calculation not working
                if (reviewHBMs != null && reviewHBMs.size() > 0) {
                    ReviewHBM reviewHBM = reviewHBMs.get(0);
                    rating = ServiceUtil.getRating(reviewHBM.getRatings());
                }/*w w w . jav a2 s  . c om*/

                productHBM.setRating(rating);
                productHBMList.add(productHBM);
            }

            return productHBMList;
        }
    });

    return productList;
}