List of usage examples for org.hibernate.criterion DetachedCriteria addOrder
public DetachedCriteria addOrder(Order order)
From source file:org.onecmdb.core.internal.storage.expression.OrderExpression.java
License:Open Source License
public DetachedCriteria getAttributeCriteria() { DetachedCriteria crit = DetachedCriteria.forClass(BasicAttribute.class); DetachedCriteria ciIdProjection = getCiCriteria().setProjection(Projections.property("longId")); crit.add(Property.forName("ownerId").in(ciIdProjection)); crit.add(Expression.eq("alias", attrAlias)); if (ascending) { crit.addOrder(Order.asc(attrType)); } else {/*from w ww . j av a 2 s .c o m*/ crit.addOrder(Order.desc(attrType)); } return (crit); }
From source file:org.onecmdb.core.internal.storage.hibernate.HibernateDao.java
License:Open Source License
public QueryResult<ICi> query(QueryCriteria criteria, boolean count) { DetachedCriteria hibCiCriteria = DetachedCriteria.forClass(ConfigurationItem.class); DetachedCriteria hibAttributeCriteria = DetachedCriteria.forClass(BasicAttribute.class); // Search in the db... if (criteria.getOffspringOfId() != null) { try {/*from w w w.j av a 2 s. co m*/ // Query for an unique id. Long longId = Long.parseLong(criteria.getOffspringOfId()); hibCiCriteria.add(Expression.eq("derivedFromId", longId)); } catch (NumberFormatException e) { log.warn("QueryCriteria contained not a long offspringId <" + criteria.getCiId()); throw new IllegalArgumentException("Not a correct long ci id <" + criteria.getCiId()); } } else if (criteria.getOffspringOfAlias() != null) { ICi ci = findCiByAlias(new Path<String>(criteria.getOffspringOfAlias())); if (criteria.getOffspringDepth() != null) { if (ci == null) { // Is an error, but we don't throw an exception, instead it will return empty/0 DetachedCriteria hibAliasCiCriteria = DetachedCriteria.forClass(ConfigurationItem.class); hibAliasCiCriteria.add(Expression.eq("alias", criteria.getOffspringOfAlias())); DetachedCriteria idCriteria = hibAliasCiCriteria.setProjection(Projections.property("longId")); hibCiCriteria.add(Property.forName("derivedFromId").in(idCriteria)); } else { // TODO: append %/%/% according to offspring depth. hibCiCriteria.add(Expression.ilike("templatePath", ci.getTemplatePath() + "/%")); } } else { if (ci != null) { hibCiCriteria.add(Expression.eq("derivedFromId", ci.getId().asLong())); } else { hibCiCriteria.add(Expression.eq("derivedFromId", new Long(0))); } } //hibAttributeCriteria.add(Expression.eq("alias", criteria.getOffspringOfAlias())); } if (criteria.getCiAlias() != null) { hibCiCriteria.add(Expression.eq("alias", criteria.getCiAlias())); } else if (criteria.getCiId() != null) { try { // Query for an unique id. Long longId = Long.parseLong(criteria.getCiId()); hibCiCriteria.add(Expression.eq("longId", longId)); } catch (NumberFormatException e) { log.warn("QueryCriteria contained not a long ci id <" + criteria.getCiId()); throw new IllegalArgumentException("Not a correct long ci id <" + criteria.getCiId()); } /* if (ci == null || ci instanceof IAttribute) { if (count) { result.setTotalHits(0); } } else { if (count) { result.setTotalHits(1); } result.add(ci); } return(result); */ } if (criteria.getMatchType() != null) { ICi type = findCiByAlias(new Path<String>(criteria.getMatchType())); if (type != null) { Disjunction orAttribute = Restrictions.disjunction(); String path = type.getTemplatePath(); String paths[] = path.split("/"); if (paths.length > 1) { for (int i = 1; i < paths.length; i++) { orAttribute.add(Expression.ilike("typeName", "%#" + paths[i], MatchMode.START)); } DetachedCriteria typeCrit = DetachedCriteria.forClass(BasicAttribute.class); typeCrit.add(Expression.isNull("derivedFromId")); typeCrit.add(orAttribute); DetachedCriteria idCrit = typeCrit.setProjection(Projections.property("ownerId")); hibCiCriteria.add(Property.forName("longId").in(idCrit)); if (criteria.getMatchCiPath() != null) { String idPath = ""; String ciPath[] = criteria.getMatchCiPath().split("/"); if (ciPath.length > 0) { for (int i = 0; i < ciPath.length; i++) { ICi ci = findCiByAlias(new Path<String>(ciPath[i])); if (ci != null) { idPath += "/" + ci.getId().asLong(); } } // TODO: append %/%/% according to offspring depth. hibCiCriteria.add(Expression.ilike("templatePath", idPath + "/%")); } } } } } if (criteria.isMatchCiTemplates() && criteria.isMatchCiInstances()) { // Search Both. } else if (criteria.isMatchCiTemplates()) { hibCiCriteria.add(Expression.eq("isBlueprint", Boolean.TRUE)); } else if (criteria.isMatchCiInstances()) { hibCiCriteria.add(Expression.eq("isBlueprint", Boolean.FALSE)); } if (criteria.isMatchAttributeTemplates() && criteria.isMatchAttributeInstances()) { // Search both } else if (criteria.isMatchAttributeTemplates()) { hibAttributeCriteria.add(Expression.eq("isBlueprint", Boolean.TRUE)); } else if (criteria.isMatchAttributeInstances()) { hibAttributeCriteria.add(Expression.eq("isBlueprint", Boolean.FALSE)); } if (criteria.getText() != null) { Disjunction orAttribute = Restrictions.disjunction(); Disjunction orCi = Restrictions.disjunction(); boolean orAttributeAdded = false; boolean orCiAdded = false; if (criteria.isTextMatchAlias()) { orCi.add(Expression.ilike("alias", criteria.getText(), MatchMode.ANYWHERE)); orAttribute.add(Expression.ilike("alias", criteria.getText(), MatchMode.ANYWHERE)); orAttributeAdded = true; orCiAdded = true; } if (criteria.isTextMatchDescription()) { orCi.add(Expression.ilike("description", criteria.getText(), MatchMode.ANYWHERE)); orAttribute.add(Expression.ilike("description", criteria.getText(), MatchMode.ANYWHERE)); orAttributeAdded = true; orCiAdded = true; } if (criteria.isTextMatchValue()) { orAttribute.add(Expression.ilike("valueAsString", criteria.getText(), MatchMode.ANYWHERE)); orAttributeAdded = true; // Enable Attribute serach.... criteria.setMatchAttribute(true); } /* DetachedCriteria idCriteria = hibAttributeCriteria.setProjection(Projections.property("ownerId")); orCi.add(Property.forName("longId").in(idCriteria)); */ if (orAttributeAdded) { if (criteria.getMatchAttributeAlias() != null) { hibAttributeCriteria.add(Expression.eq("alias", criteria.getMatchAttributeAlias())); } hibAttributeCriteria.add(orAttribute); DetachedCriteria idCriteria = hibAttributeCriteria.setProjection(Projections.property("ownerId")); orCi.add(Property.forName("longId").in(idCriteria)); orCiAdded = true; } if (orCiAdded) { hibCiCriteria.add(orCi); } } QueryResult<ICi> result = new QueryResult<ICi>(); /* if (criteria.isMatchAttribute()) { DetachedCriteria idCriteria = hibAttributeCriteria.setProjection(Projections.property("ownerId")); hibCiCriteria.add(Property.forName("longId").in(idCriteria)); } */ // Search ICi. Session session = getSession(); try { Profiler.start("QueryCi():"); if (count) { Criteria hibCriteria = hibCiCriteria.getExecutableCriteria(session); hibCriteria.setProjection(Projections.rowCount()); List list = hibCriteria.list(); if (list != null && !list.isEmpty()) { Integer itemCount = ((Integer) list.get(0)).intValue(); result.setTotalHits(itemCount); } } else { if (criteria.getOrderAttAlias() != null) { DetachedCriteria idCriteria = hibCiCriteria.setProjection(Projections.property("longId")); DetachedCriteria attr = DetachedCriteria.forClass(BasicAttribute.class); attr.add(Expression.eq("alias", criteria.getOrderAttAlias())); attr.add(Property.forName("ownerId").in(idCriteria)); if (criteria.isOrderAscending()) { attr.addOrder(Order.asc(criteria.getOrderType())); } else { attr.addOrder(Order.desc(criteria.getOrderType())); } Criteria attrCriteria = attr.getExecutableCriteria(session); if (criteria.getMaxResult() != null) { attrCriteria.setMaxResults(criteria.getMaxResult()); } if (criteria.getFirstResult() != null) { attrCriteria.setFirstResult(criteria.getFirstResult()); } List<IAttribute> attrs = attrCriteria.list(); for (IAttribute a : attrs) { result.add(a.getOwner()); } } else { hibCiCriteria.addOrder(Order.asc("alias")); Criteria hibCriteria = hibCiCriteria.getExecutableCriteria(session); if (criteria.getMaxResult() != null) { hibCriteria.setMaxResults(criteria.getMaxResult()); } if (criteria.getFirstResult() != null) { hibCriteria.setFirstResult(criteria.getFirstResult()); } List objects = hibCriteria.list(); result.addAll(objects); } } } finally { Profiler.stop(); closeSession(session); } return (result); }
From source file:org.onecmdb.core.utils.graph.handler.QueryHandler.java
License:Open Source License
private QueryResult executeQuery(GraphQuery query, ItemSelector selector) { QueryResult result = new QueryResult(); if (log.isDebugEnabled()) { log.debug(toXML(query, 0));/*w w w . java 2 s . co m*/ } long t1 = System.currentTimeMillis(); QueryExpression expr = getExpression(query, selector); if (expr.empty) { log.debug("Selector:" + selector.getTemplateAlias() + " Empty !"); result.matches = Collections.EMPTY_LIST; result.totalCount = 0; return (result); } DetachedCriteria crit = expr.criteria; QueryExpression exprCopy = getExpression(query, selector); DetachedCriteria critCopy = exprCopy.criteria; // Special handling here for RFC... if (selector instanceof ItemRFCSelector) { crit.addOrder(Order.desc("ts")); } if (selector instanceof ItemTransactionSelector) { crit.addOrder(Order.desc("endTs")); } boolean attributeOrder = false; if (selector instanceof ItemOffspringSelector) { if (selector.getOrderInfo() != null) { OrderInfo info = selector.getOrderInfo(); if (info.getCiAttr() != null) { if (info.getCiAttr().equals("displayName")) { DetachedCriteria newCrit = getDisplayNameOrder(selector.getTemplateAlias(), crit, info); if (newCrit != null) { crit = newCrit; attributeOrder = true; } else { info.setCiAttr("displayNameExpression"); } } if (!attributeOrder) { if (info.isDescenden()) { crit.addOrder(Order.desc(info.getCiAttr())); } else { crit.addOrder(Order.asc(info.getCiAttr())); } } } else { crit = getAttributeOrderCriteria(selector.getTemplateAlias(), crit, critCopy, info); attributeOrder = true; } } else { crit.addOrder(Order.desc("lastModified")); } } List matches = null; matches = this.msvc.queryCrtiteria(crit, selector.getPageInfo()); // Handle attribute order.... if (attributeOrder) { final OrderInfo info = selector.getOrderInfo(); List ciMatches = new ArrayList(); if (info.getAttrType().equals("complex")) { if (false) { Collections.sort(matches, new Comparator<IAttribute>() { public int compare(IAttribute o1, IAttribute o2) { try { IValue v1 = o1.getValue(); IValue v2 = o2.getValue(); String n1 = v1.getDisplayName(); String n2 = v2.getDisplayName(); if (info.isDescenden()) { return (n2.compareTo(n1)); } else { return (n1.compareTo(n2)); } } catch (Throwable t) { return (0); } } }); for (Object o : matches) { if (o instanceof IAttribute) { ciMatches.add(((IAttribute) o).getOwner()); } } } else { List<Long> targetIds = new ArrayList<Long>(); List<Long> targetAttrOwnerIds = new ArrayList<Long>(); for (Object o : matches) { if (o instanceof BasicAttribute) { targetAttrOwnerIds.add(((BasicAttribute) o).getOwnerId()); } } if (targetAttrOwnerIds.size() > 0) { crit = getBackComplexAttributeOrder(targetAttrOwnerIds, critCopy, info); matches = this.msvc.queryCrtiteria(crit, selector.getPageInfo()); Collections.sort(matches, new Comparator<IAttribute>() { public int compare(IAttribute o1, IAttribute o2) { try { IValue v1 = o1.getValue(); IValue v2 = o2.getValue(); String n1 = v1.getDisplayName(); String n2 = v2.getDisplayName(); if (info.isDescenden()) { return (n2.compareTo(n1)); } else { return (n1.compareTo(n2)); } } catch (Throwable t) { return (0); } } }); for (Object o : matches) { if (o instanceof IAttribute) { ciMatches.add(((IAttribute) o).getOwner()); } } } } } else { // here we receives IAttribute in the correct order.. // Need to fetch it's parent. for (Object o : matches) { if (o instanceof IAttribute) { ciMatches.add(((IAttribute) o).getOwner()); } } } matches = ciMatches; } long t2 = System.currentTimeMillis(); int totalCount = -1; if (selector.getPageInfo() != null) { // Need to do this again else the criteria is already used... // Don't count null values. if (attributeOrder && selector.getOrderInfo().getAttrType().equals("complex")) { ItemAndGroupConstraint and = new ItemAndGroupConstraint(); ItemNotConstraint not = new ItemNotConstraint(); AttributeValueConstraint aV = new AttributeValueConstraint(); aV.setOperation(AttributeValueConstraint.IS_NULL); aV.setAlias(selector.getOrderInfo().getAttrAlias()); not.applyConstraint(aV); and.add(not); ItemSelector prim = query.fetchPrimarySelectors(); if (prim.fetchConstraint() != null) { and.add(prim.fetchConstraint()); } prim.applyConstraint(and); } QueryExpression expr2 = getExpression(query, selector); totalCount = this.msvc.queryCrtiteriaCount(expr2.criteria); } long t3 = System.currentTimeMillis(); log.info("Selector:" + selector.getTemplateAlias() + " Found " + matches.size() + "items, time:" + (t2 - t1) + "ms, totalCount=" + totalCount + ", time=" + (t3 - t2) + "ms"); result.matches = matches; result.totalCount = totalCount; return (result); }
From source file:org.onecmdb.core.utils.graph.handler.QueryHandler.java
License:Open Source License
private DetachedCriteria getAttributeOrderCriteria(String template, DetachedCriteria ciCrit, DetachedCriteria ci2Crit, OrderInfo info) { if (info.getAttrType().equals("complex")) { return (getComplexAttributeOrderCriteria2(template, ciCrit, ci2Crit, info)); }//from w w w . j a v a 2 s.c o m DetachedCriteria crit = DetachedCriteria.forClass(BasicAttribute.class); DetachedCriteria ciIdProjection = ciCrit.setProjection(Projections.property("longId")); crit.add(Property.forName("ownerId").in(ciIdProjection)); crit.add(Expression.eq("alias", info.getAttrAlias())); if (info.isDescenden()) { crit.addOrder(Order.desc(info.getAttrType())); } else { crit.addOrder(Order.asc(info.getAttrType())); } return (crit); }
From source file:org.onecmdb.core.utils.graph.handler.QueryHandler.java
License:Open Source License
private DetachedCriteria getBackComplexAttributeOrder(List<Long> attrOwnerId, DetachedCriteria ci2Crit, OrderInfo info) {/*from w ww . j a va 2 s . com*/ DetachedCriteria targetCrit = DetachedCriteria.forClass(ConfigurationItem.class); targetCrit.add(Property.forName("longId").in(attrOwnerId)); DetachedCriteria refCrit = DetachedCriteria.forClass(ConfigurationItem.class); refCrit.add(Property.forName("targetId").in(targetCrit.setProjection(Projections.property("longId")))); DetachedCriteria attrCrit = DetachedCriteria.forClass(BasicAttribute.class); attrCrit.add(Property.forName("valueAsLong").in(refCrit.setProjection(Projections.property("longId")))); attrCrit.add(Property.forName("ownerId").in(ci2Crit.setProjection(Projections.property("longId")))); attrCrit.add(Expression.eq("alias", info.getAttrAlias())); attrCrit.addOrder(Order.desc("longId")); return (attrCrit); }
From source file:org.openremote.beehive.api.service.impl.GenericDAO.java
License:Open Source License
/** * Gets the by max id.//from w ww . ja v a 2s .c om * * @param clazz the clazz * * @return the by max id */ @SuppressWarnings("unchecked") public <T> T getByMaxId(Class<T> clazz) { List retList = new ArrayList(); DetachedCriteria criteria = DetachedCriteria.forClass(clazz); criteria.addOrder(Order.desc("oid")); retList = getHibernateTemplate().findByCriteria(criteria, 0, 1); if (retList != null && retList.size() > 0) { return (T) retList.get(0); } else { return null; } }
From source file:org.openremote.beehive.api.service.impl.SyncHistoryServiceImpl.java
License:Open Source License
/** * {@inheritDoc}//from www . ja v a 2s.c o m */ public SyncHistory getLatestByType(String type) { DetachedCriteria criteria = DetachedCriteria.forClass(SyncHistory.class); criteria.addOrder(Order.desc("oid")); criteria.add(Restrictions.eq("type", type)); return genericDAO.findOneByDetachedCriteria(criteria); }
From source file:org.openremote.beehive.api.service.impl.SyncHistoryServiceImpl.java
License:Open Source License
/** * {@inheritDoc}/*from w w w .j a va2s . com*/ */ public SyncHistory getLastSyncByType(String type) { DetachedCriteria criteria = DetachedCriteria.forClass(SyncHistory.class); criteria.addOrder(Order.desc("oid")); criteria.add(Restrictions.eq("type", type)); criteria.add(Restrictions.ne("status", "running")); return genericDAO.findOneByDetachedCriteria(criteria); }
From source file:org.reusables.access.AbstractHibernateRepository.java
License:Apache License
@Override public List<T> findAll(final String orderByPropertyName) // TODO cachable boolean { final DetachedCriteria crit = DetachedCriteria.forClass(this.entityClass); if (orderByPropertyName != null) { crit.addOrder(Order.asc(orderByPropertyName)); }/*ww w . jav a 2 s . co m*/ return findByCriteria(crit); }
From source file:org.sakaiproject.evaluation.dao.EvaluationDaoImpl.java
License:Educational Community License
/** * Get item groups contained within a specific group<br/> * <b>Note:</b> If parent is null then get all the highest level groups * /* w ww. ja va 2s . co m*/ * @param parentItemGroupId the unique id of an {@link EvalItemGroup}, if null then get all the highest level groups * @param userId the internal user id (not username) * @param includeEmpty if true then include all groups (even those with nothing in them), else return only groups * which contain other groups or other items * @param includeExpert if true then include expert groups only, else include non-expert groups only * @return a List of {@link EvalItemGroup} objects, ordered by title alphabetically */ public List<EvalItemGroup> getItemGroups(Long parentItemGroupId, String userId, boolean includeEmpty, boolean includeExpert) { DetachedCriteria dc = DetachedCriteria.forClass(EvalItemGroup.class) .add(Expression.eq("expert", includeExpert)); if (parentItemGroupId == null) { dc.add(Expression.isNull("parent")); } else { dc.add(Property.forName("parent.id").eq(parentItemGroupId)); } if (!includeEmpty) { String hqlQuery = "select distinct eig.parent.id from EvalItemGroup eig where eig.parent is not null"; List<?> parentIds = getHibernateTemplate().find(hqlQuery); // only include categories with items OR groups using them as a parent dc.add(Restrictions.disjunction().add(Property.forName("groupItems").isNotEmpty()) .add(Property.forName("id").in(parentIds))); } dc.addOrder(Order.asc("title")); List<?> things = getHibernateTemplate().findByCriteria(dc); List<EvalItemGroup> results = new ArrayList<>(); for (Object object : things) { results.add((EvalItemGroup) object); } return results; }