List of usage examples for org.hibernate.criterion Restrictions sizeEq
public static Criterion sizeEq(String propertyName, int size)
From source file:ca.qc.cegepoutaouais.tge.pige.server.ManagementServiceImpl.java
License:Open Source License
@Override public List<Category> getCategories(Category parent, Boolean includeUnclassified) throws PigeException { logger.debug("Rcupration des catgories..."); Transaction tx = null;/*from w w w . ja va 2 s . c om*/ List<Category> categories = null; Session session = null; try { session = PigeHibernateUtil.openSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(Category.class); if (parent != null) { logger.debug("category != null: " + parent.getName()); criteria.add(Restrictions.eq(Category.PARENT_REF, parent)); } else { criteria.add(Restrictions.isNull(Category.PARENT_REF)); } criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); categories = (List) criteria.addOrder(Order.asc(Category.NAME_REF)).list(); if (categories != null) { for (Category c : categories) { Criteria itemCrit = session.createCriteria(Item.class); itemCrit.createCriteria(Item.CATEGORIES_REF) .add(Restrictions.like(Category.PATH_REF, c.getPath(), MatchMode.START)); itemCrit.setProjection(Projections.distinct(Projections.rowCount())); c.setItemCount((Integer) itemCrit.uniqueResult()); } } // la racine seulement. if (includeUnclassified && parent == null) { Category unclassified = new Category(); unclassified.setId(Category.UNCLASSIFIED_CATEGORY_ID); Criteria itemCrit = session.createCriteria(Item.class); itemCrit.add(Restrictions.sizeEq(Item.CATEGORIES_REF, 0)); itemCrit.setProjection(Projections.distinct(Projections.rowCount())); unclassified.setItemCount((Integer) itemCrit.uniqueResult()); categories.add(unclassified); } tx.commit(); logger.debug("Rcupration russie!"); } catch (Exception hex) { logger.error(hex); if (tx != null) { tx.rollback(); } } finally { if (session != null) { session.close(); } } return categories; }
From source file:com.bloatit.data.queries.DaoAbstractQuery.java
License:Open Source License
/** * Creates a criterion on the size of a collection. * <p>//ww w. ja v a 2s . co m * For example: <code> * createSizeCriterion(GREATER, "offers", 12) * </code> Will select elements which has more than 12 offers associated * with. * </p> * * @param cmp the comparator * @param element the element name. It must be a collection (a mapped * association). * @param nb the number on which we compare the size of the collection * @return the criterion */ protected final Criterion createSizeCriterion(final Comparator cmp, final String element, final int nb) { switch (cmp) { case EQUAL: return Restrictions.sizeEq(element, nb); case LESS: return Restrictions.sizeLt(element, nb); case LESS_EQUAL: return Restrictions.sizeLe(element, nb); case GREATER: return Restrictions.sizeGt(element, nb); case GREATER_EQUAL: return Restrictions.sizeGe(element, nb); default: return Restrictions.sizeEq(element, nb); } }
From source file:com.bloatit.data.queries.DaoOfferQuery.java
License:Open Source License
/** * Add a restriction on the milestone number. */ public void withoutMilestones() { add(Restrictions.sizeEq("milestones", 1)); }
From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java
License:Apache License
/** * Element Start SAX ContentHandler Method. * @param uri//w w w.j a v a 2 s.c o m * @param localName * @param qName * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) * @throws SAXException * TODO: Document supported tags in javadoc. */ @SuppressWarnings({ "unchecked" }) public void startElement(String uri, String localNameX, String qName, Attributes attrs) throws SAXException { if ("Query".equalsIgnoreCase(qName)) { queryName = attrs.getValue("name"); rootElementName = queryName; } else if ("Class".equalsIgnoreCase(qName)) { processCriteria(attrs); } else if ("Union".equalsIgnoreCase(qName)) { inDetached = true; DetachedCriteria dc = DetachedCriteria.forEntityName(className); criteriaStack.push(dc); } else if ("NamedQuery".equalsIgnoreCase(qName)) { isNamedQuery = true; namedQuery = attrs.getValue("name"); rootElementName = namedQuery; try { query = session.getNamedQuery(namedQuery); } catch (HibernateException he) { throw new SAXException("Failed to retrieve named query[" + namedQuery + "]", he); } } else if ("qparam".equalsIgnoreCase(qName)) { processQueryBind(attrs); } else if ("Join".equalsIgnoreCase(qName)) { processCriteria(attrs); } else if ("Projections".equalsIgnoreCase(qName)) { startProjection(attrs); } else if ("Projection".equalsIgnoreCase(qName)) { addProjection(attrs); } else if ("Order".equalsIgnoreCase(qName)) { if (isRowCountOnly() == false) { try { String name = attrs.getValue("name"); String type = attrs.getValue("type"); ((Criteria) criteriaStack.peek()) .addOrder(type.equalsIgnoreCase("asc") ? Order.asc(name) : Order.desc(name)); } catch (Exception e) { throw new SAXException("Unable To Parse GreaterThan:" + attrs.getValue("name"), e); } } } else if ("GreaterThan".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.gt(operator.getName(), operator.getNativeValue())); } catch (Exception e) { throw new SAXException("Unable To Parse GreaterThan:" + attrs.getValue("name"), e); } } else if ("GreaterThanOrEqual".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.ge(operator.getName(), operator.getNativeValue())); } catch (Exception e) { throw new SAXException("Unable To Parse GreaterThanOrEqual:" + attrs.getValue("name"), e); } } else if ("LessThan".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.lt(operator.getName(), operator.getNativeValue())); } catch (Exception e) { throw new SAXException("Unable To Parse LessThan:" + attrs.getValue("name"), e); } } else if ("LessThanOrEqual".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.le(operator.getName(), operator.getNativeValue())); } catch (Exception e) { throw new SAXException("Unable To Parse LessThanOrEqual:" + attrs.getValue("name"), e); } } else if ("Equals".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); if ("true".equalsIgnoreCase(attrs.getValue("not"))) { addCriterion(Restrictions.not(Restrictions.eq(operator.getName(), operator.getNativeValue()))); } else { addCriterion(Restrictions.eq(operator.getName(), operator.getNativeValue())); } } catch (Exception e) { throw new SAXException("Unable To Parse Equals:" + attrs.getValue("name"), e); } } else if ("Alias".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); ((Criteria) criteriaStack.peek()).createAlias(operator.getName(), operator.getValue()); } catch (Exception e) { throw new SAXException("Unable To Create Alias:" + attrs.getValue("name"), e); } } else if ("GreaterThanProperty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.gtProperty(operator.getName(), operator.getName2())); } catch (Exception e) { throw new SAXException("Unable To Parse GreaterThanProperty:" + attrs.getValue("name"), e); } } else if ("GreaterThanOrEqualProperty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.geProperty(operator.getName(), operator.getName2())); } catch (Exception e) { throw new SAXException("Unable To Parse GreaterThanOrEqualProperty:" + attrs.getValue("name"), e); } } else if ("LessThanProperty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.ltProperty(operator.getName(), operator.getName2())); } catch (Exception e) { throw new SAXException("Unable To Parse LessThanProperty:" + attrs.getValue("name"), e); } } else if ("LessThanOrEqualProperty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.leProperty(operator.getName(), operator.getName2())); } catch (Exception e) { throw new SAXException("Unable To Parse LessThanOrEqualProperty:" + attrs.getValue("name"), e); } } else if ("EqualsProperty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); if ("true".equalsIgnoreCase(attrs.getValue("not"))) { addCriterion( Restrictions.not(Restrictions.eqProperty(operator.getName(), operator.getName2()))); } else { addCriterion(Restrictions.eqProperty(operator.getName(), operator.getName2())); } } catch (Exception e) { throw new SAXException("Unable To Parse EqualsProperty:" + attrs.getValue("name"), e); } } else if ("Like".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.like(operator.getName(), operator.getNativeValue())); } catch (Exception e) { throw new SAXException("Unable To Parse Like:" + attrs.getValue("name"), e); } } else if ("Between".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.between(operator.getName(), operator.getNativeValue(), operator.getNativeValue2())); } catch (Exception e) { throw new SAXException("Unable To Parse Between:" + attrs.getValue("name"), e); } } else if ("IsEmpty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.isEmpty(operator.getName())); } catch (Exception e) { throw new SAXException("Unable To Parse IsEmpty:" + attrs.getValue("name"), e); } } else if ("IsNotEmpty".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.isNotEmpty(operator.getName())); } catch (Exception e) { throw new SAXException("Unable To Parse IsNotEmpty:" + attrs.getValue("name"), e); } } else if ("IsNull".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.isNull(operator.getName())); } catch (Exception e) { throw new SAXException("Unable To Parse IsNull:" + attrs.getValue("name"), e); } } else if ("IsNotNull".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); addCriterion(Restrictions.isNotNull(operator.getName())); } catch (Exception e) { throw new SAXException("Unable To Parse IsNotNull:" + attrs.getValue("name"), e); } } else if ("In".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); if (operator.isLiteral()) { addCriterion(new LiteralInExpression(operator.getName(), (String) operator.getNativeValue())); } else { addCriterion(Restrictions.in(operator.getName(), (Collection) operator.getNativeValue())); } } catch (Exception e) { throw new SAXException("Unable To Parse In:" + attrs.getValue("name"), e); } } else if ("SizeEquals".equalsIgnoreCase(qName)) { try { Operator operator = new Operator(attrs); int i = ((Integer) operator.getNativeValue()).intValue(); addCriterion(Restrictions.sizeEq(operator.getName(), i)); } catch (Exception e) { throw new SAXException("Unable To Parse SizeEquals:" + attrs.getValue("name"), e); } } else if ("Not".equalsIgnoreCase(qName)) { notStack.push(new Object()); } else if ("Or".equalsIgnoreCase(qName)) { opStack.push(Restrictions.disjunction()); } else if ("And".equalsIgnoreCase(qName)) { opStack.push(Restrictions.conjunction()); } else { throw new SAXException("Element Name[" + qName + "] Not Recognized."); } }
From source file:com.qcadoo.model.api.search.SearchRestrictions.java
License:Open Source License
/** * Creates criterion which checks if "collection" field's size is equal to given size. * /*from w w w .java 2s . c o m*/ * @param field * field * @param size * size * @return criterion */ public static SearchCriterion sizeEq(final String field, final int size) { return new SearchCriterionImpl(Restrictions.sizeEq(field, size)); }
From source file:cz.jirutka.rsql.visitor.hibernate.HibernateCriterionVisitor.java
License:Apache License
@Override public Criterion visit(ComparisonNode node) { String name = node.getSelector(); /*//from www. jav a 2s. c om Get the path and property names */ Tuple<Type, String>[] path = getPath(root, name); Type type = getType(path); boolean isPrimitive = type instanceof StringRepresentableType; boolean isCustom = type instanceof CustomType; boolean isCollection = type instanceof CollectionType; String exp = getExpression(path, isCollection); List<Object> arguments = new ArrayList<Object>(node.getArguments().size()); for (String argument : node.getArguments()) { Object value = argument; if (isPrimitive) { value = ((StringRepresentableType) type).fromStringValue((String) value); } else if (isCustom) { value = ((CustomType) type).stringToObject((String) value); } else if (isCollection) { value = IntegerType.INSTANCE.fromString((String) value); } if (value instanceof String) { value = toSqlWildcardString((String) value); } arguments.add(value); } ComparisonOperator operator = node.getOperator(); assert arguments.size() >= 1; Object firstArgument = arguments.get(0); if (operator.equals(RSQLOperators.EQUAL)) { if (!isCollection) { if (String.class.isInstance(firstArgument) && ((String) firstArgument).contains("%")) { return Restrictions.ilike(exp, firstArgument); } else { return Restrictions.eq(exp, firstArgument); } } else { return Restrictions.sizeEq(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.NOT_EQUAL)) { if (!isCollection) { if (String.class.isInstance(firstArgument) && ((String) firstArgument).contains("%")) { return Restrictions.not(Restrictions.ilike(exp, firstArgument)); } else { return Restrictions.ne(exp, firstArgument); } } else { return Restrictions.sizeNe(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.GREATER_THAN)) { if (!isCollection) { return Restrictions.gt(exp, firstArgument); } else { return Restrictions.sizeGt(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.GREATER_THAN_OR_EQUAL)) { if (!isCollection) { return Restrictions.ge(exp, firstArgument); } else { return Restrictions.sizeGe(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.LESS_THAN)) { if (!isCollection) { return Restrictions.lt(exp, firstArgument); } else { return Restrictions.sizeLt(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.LESS_THAN_OR_EQUAL)) { if (!isCollection) { return Restrictions.le(exp, firstArgument); } else { return Restrictions.sizeLe(exp, (Integer) firstArgument); } } else if (operator.equals(RSQLOperators.IN)) { if (!isCollection) { return Restrictions.in(exp, arguments); } } else if (operator.equals(RSQLOperators.NOT_IN)) { if (!isCollection) { return Restrictions.not(Restrictions.in(exp, arguments)); } } throw new IllegalArgumentException("Unknown operation " + operator.toString() + " for property" + name); }
From source file:grails.orm.HibernateCriteriaBuilder.java
License:Apache License
/** * Creates a Criterion that contrains a collection property by size * * @param propertyName The property name * @param size The size to constrain by/* ww w . j a va2s .c om*/ * * @return A Criterion instance */ public org.grails.datastore.mapping.query.api.Criteria sizeEq(String propertyName, int size) { if (!validateSimpleExpression()) { throwRuntimeException(new IllegalArgumentException("Call to [sizeEq] with propertyName [" + propertyName + "] and size [" + size + "] not allowed here.")); } propertyName = calculatePropertyName(propertyName); addToCriteria(Restrictions.sizeEq(propertyName, size)); return this; }
From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateCriterionAdapter.java
License:Apache License
protected void addSizeComparisonCriterionAdapters() { criterionAdaptors.put(Query.SizeEquals.class, new CriterionAdaptor<Query.SizeEquals>() { @Override/*from www . j av a 2s . co m*/ public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.SizeEquals criterion, String alias) { String propertyName = getPropertyName(criterion, alias); Object value = criterion.getValue(); int size = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString()); return Restrictions.sizeEq(propertyName, size); } }); criterionAdaptors.put(Query.SizeGreaterThan.class, new CriterionAdaptor<Query.SizeGreaterThan>() { @Override public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.SizeGreaterThan criterion, String alias) { String propertyName = getPropertyName(criterion, alias); Object value = criterion.getValue(); int size = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString()); return Restrictions.sizeGt(propertyName, size); } }); criterionAdaptors.put(Query.SizeGreaterThanEquals.class, new CriterionAdaptor<Query.SizeGreaterThanEquals>() { @Override public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.SizeGreaterThanEquals criterion, String alias) { String propertyName = getPropertyName(criterion, alias); Object value = criterion.getValue(); int size = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString()); return Restrictions.sizeGe(propertyName, size); } }); criterionAdaptors.put(Query.SizeLessThan.class, new CriterionAdaptor<Query.SizeLessThan>() { @Override public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.SizeLessThan criterion, String alias) { String propertyName = getPropertyName(criterion, alias); Object value = criterion.getValue(); int size = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString()); return Restrictions.sizeLt(propertyName, size); } }); criterionAdaptors.put(Query.SizeLessThanEquals.class, new CriterionAdaptor<Query.SizeLessThanEquals>() { @Override public Criterion toHibernateCriterion(AbstractHibernateQuery hibernateQuery, Query.SizeLessThanEquals criterion, String alias) { String propertyName = getPropertyName(criterion, alias); Object value = criterion.getValue(); int size = value instanceof Number ? ((Number) value).intValue() : Integer.parseInt(value.toString()); return Restrictions.sizeLe(propertyName, size); } }); }
From source file:org.javamexico.dao.hib3.QuestionDAO.java
License:Open Source License
public List<Pregunta> getPreguntasSinResponder(int limit) { Session sess = sfact.getCurrentSession(); @SuppressWarnings("unchecked") List<Pregunta> qus = sess.createCriteria(Pregunta.class).add(Restrictions.sizeEq("respuestas", 0)) .addOrder(Order.desc("fechaPregunta")).setMaxResults(limit).list(); return qus;//from w w w . java 2 s . c o m }
From source file:org.openbravo.costing.LandedCostProcess.java
License:Open Source License
private void doChecks(LandedCost landedCost, JSONObject message) { // Check there are Receipt Lines and Costs. OBCriteria<LandedCost> critLC = OBDal.getInstance().createCriteria(LandedCost.class); critLC.add(Restrictions.sizeEq(LandedCost.PROPERTY_LANDEDCOSTCOSTLIST, 0)); critLC.add(Restrictions.eq(LandedCost.PROPERTY_ID, landedCost.getId())); if (critLC.uniqueResult() != null) { throw new OBException(OBMessageUtils.messageBD("LandedCostNoCosts")); }/* w w w . ja v a 2 s .c o m*/ critLC = OBDal.getInstance().createCriteria(LandedCost.class); critLC.add(Restrictions.sizeEq(LandedCost.PROPERTY_LANDEDCOSTRECEIPTLIST, 0)); critLC.add(Restrictions.eq(LandedCost.PROPERTY_ID, landedCost.getId())); if (critLC.uniqueResult() != null) { throw new OBException(OBMessageUtils.messageBD("LandedCostNoReceipts")); } // Check that all related receipt lines with movementqty >=0 have their cost already calculated. StringBuffer where = new StringBuffer(); where.append(" as lcr "); where.append("\n left join lcr." + LCReceipt.PROPERTY_GOODSSHIPMENT + " lcrr"); where.append("\n left join lcr." + LCReceipt.PROPERTY_GOODSSHIPMENTLINE + " lcrrl"); where.append("\n where exists ("); where.append("\n select 1"); where.append("\n from " + MaterialTransaction.ENTITY_NAME + " as trx"); where.append("\n join trx." + MaterialTransaction.PROPERTY_GOODSSHIPMENTLINE + " as iol"); where.append("\n where trx." + MaterialTransaction.PROPERTY_ISCOSTCALCULATED + " = false"); where.append("\n and iol." + ShipmentInOutLine.PROPERTY_MOVEMENTQUANTITY + " >= 0"); where.append("\n and (lcrrl is null"); where.append("\n or iol = lcrrl)"); where.append("\n and (lcrr is null"); where.append("\n or (lcrrl is null "); where.append("\n and iol." + ShipmentInOutLine.PROPERTY_SHIPMENTRECEIPT + " = lcrr"); where.append("\n ))"); where.append("\n )"); where.append("\n and lcr." + LCReceipt.PROPERTY_LANDEDCOST + " = :landedcost"); OBQuery<LCReceipt> qryTrx = OBDal.getInstance().createQuery(LCReceipt.class, where.toString()); qryTrx.setNamedParameter("landedcost", landedCost); if (qryTrx.count() > 0) { String strReceiptNumbers = ""; for (LCReceipt lcrl : qryTrx.list()) { if (strReceiptNumbers.length() > 0) { strReceiptNumbers += ", "; } if (lcrl.getGoodsShipmentLine() != null) { strReceiptNumbers += lcrl.getGoodsShipmentLine().getIdentifier(); } else { strReceiptNumbers += lcrl.getGoodsShipment().getIdentifier(); } } String errorMsg = OBMessageUtils.messageBD("LandedCostReceiptWithoutCosts"); log.error("Processed and Cost Calculated check error"); throw new OBException(errorMsg + "\n" + strReceiptNumbers); } // Execute checks added implementing LandedCostProcessCheck interface. for (LandedCostProcessCheck checksInstance : landedCostProcessChecks) { checksInstance.doCheck(landedCost, message); } }