List of usage examples for org.hibernate.criterion Restrictions le
public static SimpleExpression le(String propertyName, Object value)
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 ww w . j av a2 s . c o 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.mycompany.CRMFly.hibernateAccess.ProjectsDAOImpl.java
public List<Projects> getProjectsOnDate(Date date) { return sessionFactory.getCurrentSession().createCriteria(Projects.class) .add(Restrictions.le("begin_date", date)).add(Restrictions.ge("end_date", date)).list(); }
From source file:com.mycompany.CRMFly.hibernateAccess.ProjectsDAOImpl.java
public List<Projects> getProjectsForEmployeeOnDate(Long id, Date date) { org.hibernate.Session sess = sessionFactory.getCurrentSession(); sess.enableFetchProfile("projects-with-employees"); return sess.createCriteria(Projects.class).add(Restrictions.le("begin_date", date)) .add(Restrictions.ge("end_date", date)).createCriteria("participants") .add(Restrictions.eq("id", id)).list(); }
From source file:com.nec.harvest.service.impl.BudgetPerformanceServiceImpl.java
License:Open Source License
/** {@inheritDoc} */ @Override/*from w w w . ja va 2 s . c o m*/ 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.onecheckoutV1.scheduler.SchedulerTransactionOcoBean.java
public void startSchedulerDaily() { PropertiesConfiguration config = OneCheckoutProperties.getOneCheckoutConfig(); String on = config.getString("TRANSACTION.OCO.SCHEDULER.", "TRUE"); if (on.equalsIgnoreCase("FALSE")) { OneCheckoutLogger.log("OneCheckoutV1 - scheduller of Transaction OCO disabled"); return;/*from w w w . j a v a 2 s.co m*/ } int maxrows = config.getInt("NOTIFY.STATUS.ROWS", 50); Calendar max = Calendar.getInstance(); max.add(Calendar.HOUR, -24); Date executeTime = max.getTime(); Criteria criterias = getSession().createCriteria(Transactions.class); criterias.createAlias("merchantPaymentChannel", "mpc"); criterias.createAlias("mpc.merchants", "m"); criterias.createAlias("mpc.paymentChannel", "pc"); criterias.add(Restrictions.le("incRequestdatetime", executeTime)); criterias.addOrder(Order.desc("incRequestdatetime")); criterias.setMaxResults(maxrows); OneCheckoutLogger.log("TRANSACTION.beforeToday.date" + executeTime + "]"); List<Transactions> trxListOco = (List<Transactions>) criterias.list(); if (trxListOco == null || trxListOco.isEmpty()) { OneCheckoutLogger.log("SchedulerTransactionOcoBean.startSchedulerExecutor : 0 transactions"); return; } for (Transactions transactions : trxListOco) { if (StringUtils.isEmpty(transactions.getDokuResponseCode()) && transactions.getTransactionsStatus() == null) { OneCheckoutErrorMessage failedMsg = OneCheckoutErrorMessage.UNKNOWN; String logPrefix = "TransactionOcoScheduler_" + transactions.getMerchantPaymentChannel().getMerchants().getMerchantCode() + "_" + transactions.getIncTransidmerchant(); SecurityAssociation.setPrincipal(new OneCheckoutPrincipal(logPrefix)); failedMsg = OneCheckoutErrorMessage.FAILED_TRANSACTION_VIA_SCHEDULER; transactions.setDokuResponseCode(failedMsg.value()); transactions.setTransactionsStatus(OneCheckoutTransactionStatus.FAILED.value()); oneCheckoutV1QueryHelperBeanLocal.updateTransactions(transactions); OneCheckoutLogger.log("SchedulerTransactionOcoBean : update finished trx : "); } } SecurityAssociation.clear(); }
From source file:com.ongame.pokerstore.model.HibernateStoreDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<String> getOutOfStockProductIds() { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Product.class); criteria.add(Restrictions.le("inventory", 0L)).setProjection(Projections.property("id")); return (List<String>) criteria.list(); }
From source file:com.pontorural.pedidovenda.repository.Pedidos.java
@SuppressWarnings("unchecked") public List<Pedido> filtrados(PedidoFilter filtro) { Session session = this.manager.unwrap(Session.class); Criteria criteria = session.createCriteria(Pedido.class); if (filtro.getNumeroDe() != null) { // id deve ser maior ou igual (ge = greater or equals) a filtro.numeroDe criteria.add(Restrictions.ge("codigo", filtro.getNumeroDe())); }//from w w w . j ava 2 s.co m if (filtro.getNumeroAte() != null) { // id deve ser menor ou igual (le = lower or equal) a filtro.numeroDe criteria.add(Restrictions.le("codigo", filtro.getNumeroAte())); } if (filtro.getEmissaoDe() != null) { criteria.add(Restrictions.ge("emissao", filtro.getEmissaoDe())); } if (filtro.getEmissaoAte() != null) { criteria.add(Restrictions.le("emissao", filtro.getEmissaoAte())); } return criteria.addOrder(Order.asc("codigo")).list(); }
From source file:com.ponysdk.hibernate.query.decorator.AbstractCriteriaDecorator.java
License:Apache License
@SuppressWarnings("rawtypes") @Override//from w w w. j a v a 2 s.c om public void render(final CriteriaContext context) { final Criterion field = context.getCriterion(); Criteria criteria = context.getOrderingCriteria(); final List<String> propertyNamePath = Arrays.asList(field.getPojoProperty().split(REGEX_SPLIT)); final Iterator<String> iter = propertyNamePath.iterator(); String key = null; String associationPath = null; if (propertyNamePath.size() == 1) { associationPath = iter.next(); } else while (iter.hasNext()) { key = iter.next(); if (associationPath == null) { associationPath = new String(key); } else { associationPath += "." + key; } if (iter.hasNext()) { criteria = criteria.createCriteria(associationPath, key, CriteriaSpecification.INNER_JOIN); associationPath = new String(key); } } final T value = getObjectValue(field); ComparatorType comparator = field.getComparator(); if (value != null) { if (value.toString().contains("%")) { comparator = ComparatorType.LIKE; } } if (field.getValue() != null || field.getComparator() == ComparatorType.IS_NULL || field.getComparator() == ComparatorType.IS_NOT_NULL) { switch (comparator) { case EQ: criteria.add(Restrictions.eq(associationPath, value)); break; case GE: criteria.add(Restrictions.ge(associationPath, value)); break; case GT: criteria.add(Restrictions.gt(associationPath, value)); break; case LE: criteria.add(Restrictions.le(associationPath, value)); break; case LT: criteria.add(Restrictions.lt(associationPath, value)); break; case NE: criteria.add(Restrictions.ne(associationPath, value)); break; case LIKE: criteria.add(Restrictions.ilike(associationPath, value)); break; case IS_NULL: criteria.add(Restrictions.isNull(associationPath)); break; case IS_NOT_NULL: criteria.add(Restrictions.isNotNull(associationPath)); break; case IN: if (value instanceof Collection) { criteria.add(Restrictions.in(associationPath, (Collection) value)); } else if (value instanceof Object[]) { criteria.add(Restrictions.in(associationPath, (Object[]) value)); } else { log.warn("Type not allowed for IN clause: " + value.getClass() + ", value: " + value); } break; default: log.warn("Restriction not supported: " + comparator); break; } } switch (field.getSortingType()) { case ASCENDING: criteria.addOrder(Order.asc(associationPath)); break; case DESCENDING: criteria.addOrder(Order.desc(associationPath)); break; case NONE: break; } }
From source file:com.qcadoo.model.api.search.SearchRestrictions.java
License:Open Source License
/** * Creates criterion which checks if field is less than or equal to given value. * //from w ww .j av a2 s.co m * @param field * field * @param value * value * @return criterion */ public static SearchCriterion le(final String field, final Object value) { return new SearchCriterionImpl(Restrictions.le(field, value)); }
From source file:com.qcadoo.model.internal.PriorityServiceImpl.java
License:Open Source License
@SuppressWarnings("unchecked") private void changePriority(final InternalDataDefinition dataDefinition, final FieldDefinition fieldDefinition, final Object databaseEntity, final int fromPriority, final int toPriority, final int diff) { Criteria criteria = getCriteria(dataDefinition, fieldDefinition, databaseEntity) .add(Restrictions.ge(fieldDefinition.getName(), fromPriority)) .add(Restrictions.le(fieldDefinition.getName(), toPriority)); List<Object> entitiesToDecrement = criteria.list(); for (Object entity : entitiesToDecrement) { int priority = (Integer) entityService.getField(entity, fieldDefinition); entityService.setField(entity, fieldDefinition, priority + diff); hibernateService.getCurrentSession().update(entity); }//from w w w. j av a 2 s . c o m }