List of usage examples for org.hibernate.criterion Restrictions isEmpty
public static Criterion isEmpty(String propertyName)
From source file:com.inkubator.hrm.dao.impl.BioDataDaoImpl.java
@Override public List<BioData> getByName(String name) { Criteria criteria = getCurrentSession().createCriteria(getEntityClass()); // criteria.createAlias("empDatas", "emp",JoinType.INNER_JOIN); Disjunction disjunction = Restrictions.disjunction(); disjunction.add(Restrictions.like("firstName", name, MatchMode.ANYWHERE)); disjunction.add(Restrictions.like("lastName", name, MatchMode.ANYWHERE)); criteria.add(disjunction);/*from www . ja v a 2 s . co m*/ criteria.add(Restrictions.isEmpty("empDatas")); criteria.addOrder(Order.asc("firstName")); criteria.setFirstResult(0); criteria.setMaxResults(7); return criteria.list(); }
From source file:com.qcadoo.model.api.search.SearchRestrictions.java
License:Open Source License
/** * Creates criterion which checks if "collection" field's size is empty. * // w w w .j av a 2 s. c o m * @param field * field * @return criterion */ public static SearchCriterion isEmpty(final String field) { return new SearchCriterionImpl(Restrictions.isEmpty(field)); }
From source file:data.dao.SequenceDao.java
public List<Sequence> findWithoutScenes() { Criteria cr = currentSession().createCriteria(getSupportedClass()); //cr.add(Restrictions.isNull("scenes")); cr.add(Restrictions.isEmpty("scenes")); return cr.list(); }
From source file:de.escidoc.core.aa.business.filter.RoleFilter.java
License:Open Source License
/** * Evaluate a CQL term node.//from w w w . j a va 2 s. c o m * * @param node CQL node * @return Hibernate query reflecting the given CQL query * @throws InvalidSearchQueryException thrown if the given search query could not be translated into a SQL query */ @Override protected Criterion evaluate(final CQLTermNode node) throws InvalidSearchQueryException { Criterion result = null; final Object[] parts = criteriaMap.get(node.getIndex()); final String value = node.getTerm(); if (parts != null && !specialCriteriaNames.contains(node.getIndex())) { result = evaluate(node.getRelation(), (String) parts[1], value, (Integer) parts[0] == COMPARE_LIKE); } else { final String columnName = node.getIndex(); if (columnName != null) { if ("limited".equals(columnName)) { result = Boolean.parseBoolean(value) ? Restrictions.isNotEmpty("scopeDefs") : Restrictions.isEmpty("scopeDefs"); } else if ("granted".equals(columnName)) { final DetachedCriteria subQuery = DetachedCriteria.forClass(RoleGrant.class, "rg"); subQuery.setProjection(Projections.rowCount()); subQuery.add(Restrictions.eqProperty("escidocRole.id", "r.id")); result = Boolean.parseBoolean(value) ? Subqueries.lt(0L, subQuery) : Subqueries.eq(0L, subQuery); } else if (columnName.equals(Constants.FILTER_CREATION_DATE) || columnName.equals(Constants.FILTER_PATH_CREATION_DATE)) { result = evaluate(node.getRelation(), "creationDate", value != null && value.length() > 0 ? new Date(new DateTime(value).getMillis()) : null, false); } else { throw new InvalidSearchQueryException("unknown filter criteria: " + columnName); } } } return result; }
From source file:de.escidoc.core.aa.business.persistence.hibernate.HibernateEscidocRoleDao.java
License:Open Source License
/** * See Interface for functional description. * * @see EscidocRoleDaoInterface #retrieveRoles(java.util.Map, int, int, java.lang.String, * de.escidoc.core.common.util.list.ListSorting) *//*from www. j ava 2 s. c o m*/ @Override public List<EscidocRole> retrieveRoles(final Map<String, Object> criterias, final int offset, final int maxResults, final String orderBy, final ListSorting sorting) throws SqlDatabaseSystemException { final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(EscidocRole.class, "r"); detachedCriteria.add(Restrictions.ne("id", EscidocRole.DEFAULT_USER_ROLE_ID)); if (criterias != null && !criterias.isEmpty()) { // ids final Set<String> roleIds = mergeSets((Set<String>) criterias.remove(Constants.DC_IDENTIFIER_URI), (Set<String>) criterias.remove(Constants.FILTER_PATH_ID)); if (roleIds != null && !roleIds.isEmpty()) { detachedCriteria.add(Restrictions.in("id", roleIds.toArray())); } // limited final String limited = (String) criterias.remove("limited"); if (limited != null) { if (Boolean.parseBoolean(limited)) { detachedCriteria.add(Restrictions.isNotEmpty("scopeDefs")); } else { detachedCriteria.add(Restrictions.isEmpty("scopeDefs")); } } // granted final String granted = (String) criterias.remove("granted"); if (granted != null) { final DetachedCriteria subQuery = DetachedCriteria.forClass(RoleGrant.class, "rg"); subQuery.setProjection(Projections.rowCount()); subQuery.add(Restrictions.eqProperty("escidocRole.id", "r.id")); if (Boolean.parseBoolean(granted)) { detachedCriteria.add(Subqueries.lt(0, subQuery)); } else { detachedCriteria.add(Subqueries.eq(0, subQuery)); } } for (final Entry<String, Object[]> stringEntry : criteriaMap.entrySet()) { final Object criteriaValue = criterias.remove(stringEntry.getKey()); if (criteriaValue != null) { final Object[] parts = stringEntry.getValue(); if (parts[0].equals(COMPARE_EQ)) { detachedCriteria.add(Restrictions.eq((String) parts[1], criteriaValue)); } else { detachedCriteria.add(Restrictions.like((String) parts[1], criteriaValue)); } } } } if (orderBy != null) { if (sorting == ListSorting.ASCENDING) { detachedCriteria.addOrder(Order.asc(propertiesNamesMap.get(orderBy))); } else if (sorting == ListSorting.DESCENDING) { detachedCriteria.addOrder(Order.desc(propertiesNamesMap.get(orderBy))); } } if (criterias != null && criterias.isEmpty()) { final List<EscidocRole> result; try { result = getHibernateTemplate().findByCriteria(detachedCriteria, offset, maxResults); } catch (final DataAccessException e) { throw new SqlDatabaseSystemException(e); } return result; } else { // unsupported filter criteria has been found, therefore the result // list must be empty. return new ArrayList<EscidocRole>(0); } }
From source file:de.iteratec.iteraplan.persistence.dao.CheckBuildingBlocksWithNoAssociationsHelper.java
License:Open Source License
/** * Helper method to add restrictions imposing that all associations of a building block either do * not exist (null) or are empty.//from ww w.j a v a 2 s.c om * * @param c * the Criteria object * @param alias * the alias of the building block * @param associations * the set of associations * @param properties * the set of properties */ public static void addRestrictionForAssociations(Criteria c, String alias, String[] associations, String[] properties) { for (String association : Arrays.asList(associations)) { //path to retrieve associated element String associationPath = alias + "." + association; //add restriction of this specific association c.add(Restrictions.or(Restrictions.isNull(associationPath), Restrictions.isEmpty(associationPath))); //mind that several c.add() produced from this iteration are implicitly combined by a logical AND } for (String property : properties) { //add restriction of this specific property c.add(Restrictions.or(Restrictions.isNull(property), Restrictions.isEmpty(property))); } }
From source file:fr.mcc.ginco.dao.hibernate.ThesaurusConceptDAO.java
License:CeCILL license
private void selectNoParents(Criteria criteria) { criteria.add(Restrictions.or(Restrictions.isNull("tc.parentConcepts"), Restrictions.isEmpty("tc.parentConcepts"))); }
From source file:grails.orm.HibernateCriteriaBuilder.java
License:Apache License
public org.grails.datastore.mapping.query.api.Criteria isEmpty(String property) { String propertyName = calculatePropertyName(property); addToCriteria(Restrictions.isEmpty(propertyName)); return this; }
From source file:grails.orm.HibernateCriteriaBuilder.java
License:Apache License
@SuppressWarnings("rawtypes") @Override//from w ww. j ava2 s . c om public Object invokeMethod(String name, Object obj) { Object[] args = obj.getClass().isArray() ? (Object[]) obj : new Object[] { obj }; if (paginationEnabledList && SET_RESULT_TRANSFORMER_CALL.equals(name) && args.length == 1 && args[0] instanceof ResultTransformer) { resultTransformer = (ResultTransformer) args[0]; return null; } if (isCriteriaConstructionMethod(name, args)) { if (criteria != null) { throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here")); } if (name.equals(GET_CALL)) { uniqueResult = true; } else if (name.equals(SCROLL_CALL)) { scroll = true; } else if (name.equals(COUNT_CALL)) { count = true; } else if (name.equals(LIST_DISTINCT_CALL)) { resultTransformer = CriteriaSpecification.DISTINCT_ROOT_ENTITY; } createCriteriaInstance(); // Check for pagination params if (name.equals(LIST_CALL) && args.length == 2) { paginationEnabledList = true; orderEntries = new ArrayList<Order>(); invokeClosureNode(args[1]); } else { invokeClosureNode(args[0]); } if (resultTransformer != null) { criteria.setResultTransformer(resultTransformer); } Object result; if (!uniqueResult) { if (scroll) { result = criteria.scroll(); } else if (count) { criteria.setProjection(Projections.rowCount()); result = criteria.uniqueResult(); } else if (paginationEnabledList) { // Calculate how many results there are in total. This has been // moved to before the 'list()' invocation to avoid any "ORDER // BY" clause added by 'populateArgumentsForCriteria()', otherwise // an exception is thrown for non-string sort fields (GRAILS-2690). criteria.setFirstResult(0); criteria.setMaxResults(Integer.MAX_VALUE); criteria.setProjection(Projections.rowCount()); int totalCount = ((Number) criteria.uniqueResult()).intValue(); // Restore the previous projection, add settings for the pagination parameters, // and then execute the query. if (projectionList != null && projectionList.getLength() > 0) { criteria.setProjection(projectionList); } else { criteria.setProjection(null); } for (Order orderEntry : orderEntries) { criteria.addOrder(orderEntry); } if (resultTransformer == null) { criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } else if (paginationEnabledList) { // relevant to GRAILS-5692 criteria.setResultTransformer(resultTransformer); } // GRAILS-7324 look if we already have association to sort by Map argMap = (Map) args[0]; final String sort = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_SORT); if (sort != null) { boolean ignoreCase = true; Object caseArg = argMap.get(GrailsHibernateUtil.ARGUMENT_IGNORE_CASE); if (caseArg instanceof Boolean) { ignoreCase = (Boolean) caseArg; } final String orderParam = (String) argMap.get(GrailsHibernateUtil.ARGUMENT_ORDER); final String order = GrailsHibernateUtil.ORDER_DESC.equalsIgnoreCase(orderParam) ? GrailsHibernateUtil.ORDER_DESC : GrailsHibernateUtil.ORDER_ASC; int lastPropertyPos = sort.lastIndexOf('.'); String associationForOrdering = lastPropertyPos >= 0 ? sort.substring(0, lastPropertyPos) : null; if (associationForOrdering != null && aliasMap.containsKey(associationForOrdering)) { addOrder(criteria, aliasMap.get(associationForOrdering) + "." + sort.substring(lastPropertyPos + 1), order, ignoreCase); // remove sort from arguments map to exclude from default processing. @SuppressWarnings("unchecked") Map argMap2 = new HashMap(argMap); argMap2.remove(GrailsHibernateUtil.ARGUMENT_SORT); argMap = argMap2; } } GrailsHibernateUtil.populateArgumentsForCriteria(grailsApplication, targetClass, criteria, argMap); PagedResultList pagedRes = new PagedResultList(criteria.list()); // Updated the paged results with the total number of records calculated previously. pagedRes.setTotalCount(totalCount); result = pagedRes; } else { result = criteria.list(); } } else { result = GrailsHibernateUtil.unwrapIfProxy(criteria.uniqueResult()); } if (!participate) { hibernateSession.close(); } return result; } if (criteria == null) createCriteriaInstance(); MetaMethod metaMethod = getMetaClass().getMetaMethod(name, args); if (metaMethod != null) { return metaMethod.invoke(this, args); } metaMethod = criteriaMetaClass.getMetaMethod(name, args); if (metaMethod != null) { return metaMethod.invoke(criteria, args); } metaMethod = criteriaMetaClass.getMetaMethod(GrailsClassUtils.getSetterName(name), args); if (metaMethod != null) { return metaMethod.invoke(criteria, args); } if (isAssociationQueryMethod(args) || isAssociationQueryWithJoinSpecificationMethod(args)) { final boolean hasMoreThanOneArg = args.length > 1; Object callable = hasMoreThanOneArg ? args[1] : args[0]; int joinType = hasMoreThanOneArg ? (Integer) args[0] : CriteriaSpecification.INNER_JOIN; if (name.equals(AND) || name.equals(OR) || name.equals(NOT)) { if (criteria == null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } logicalExpressionStack.add(new LogicalExpression(name)); invokeClosureNode(callable); LogicalExpression logicalExpression = logicalExpressionStack .remove(logicalExpressionStack.size() - 1); addToCriteria(logicalExpression.toCriterion()); return name; } if (name.equals(PROJECTIONS) && args.length == 1 && (args[0] instanceof Closure)) { if (criteria == null) { throwRuntimeException( new IllegalArgumentException("call to [" + name + "] not supported here")); } projectionList = Projections.projectionList(); invokeClosureNode(callable); if (projectionList != null && projectionList.getLength() > 0) { criteria.setProjection(projectionList); } return name; } final PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(targetClass, name); if (pd != null && pd.getReadMethod() != null) { ClassMetadata meta = sessionFactory.getClassMetadata(targetClass); Type type = meta.getPropertyType(name); if (type.isAssociationType()) { String otherSideEntityName = ((AssociationType) type) .getAssociatedEntityName((SessionFactoryImplementor) sessionFactory); Class oldTargetClass = targetClass; targetClass = sessionFactory.getClassMetadata(otherSideEntityName) .getMappedClass(EntityMode.POJO); if (targetClass.equals(oldTargetClass) && !hasMoreThanOneArg) { joinType = CriteriaSpecification.LEFT_JOIN; // default to left join if joining on the same table } associationStack.add(name); final String associationPath = getAssociationPath(); createAliasIfNeccessary(name, associationPath, joinType); // the criteria within an association node are grouped with an implicit AND logicalExpressionStack.add(new LogicalExpression(AND)); invokeClosureNode(callable); aliasStack.remove(aliasStack.size() - 1); if (!aliasInstanceStack.isEmpty()) { aliasInstanceStack.remove(aliasInstanceStack.size() - 1); } LogicalExpression logicalExpression = logicalExpressionStack .remove(logicalExpressionStack.size() - 1); if (!logicalExpression.args.isEmpty()) { addToCriteria(logicalExpression.toCriterion()); } associationStack.remove(associationStack.size() - 1); targetClass = oldTargetClass; return name; } } } else if (args.length == 1 && args[0] != null) { if (criteria == null) { throwRuntimeException(new IllegalArgumentException("call to [" + name + "] not supported here")); } Object value = args[0]; Criterion c = null; if (name.equals(ID_EQUALS)) { return eq("id", value); } if (name.equals(IS_NULL) || name.equals(IS_NOT_NULL) || name.equals(IS_EMPTY) || name.equals(IS_NOT_EMPTY)) { if (!(value instanceof String)) { throwRuntimeException(new IllegalArgumentException( "call to [" + name + "] with value [" + value + "] requires a String value.")); } String propertyName = calculatePropertyName((String) value); if (name.equals(IS_NULL)) { c = Restrictions.isNull(propertyName); } else if (name.equals(IS_NOT_NULL)) { c = Restrictions.isNotNull(propertyName); } else if (name.equals(IS_EMPTY)) { c = Restrictions.isEmpty(propertyName); } else if (name.equals(IS_NOT_EMPTY)) { c = Restrictions.isNotEmpty(propertyName); } } if (c != null) { return addToCriteria(c); } } throw new MissingMethodException(name, getClass(), args); }
From source file:net.firejack.platform.core.store.AbstractStore.java
License:Apache License
protected Criterion getRestrictions(SearchQuery query, Class<?> type) { Criterion criterion;/*from w ww. jav a2 s . c om*/ Object value = query.getValue(); QueryOperation operation = query.getOperation(); if (value != null && !(QueryOperation.FIELDEQUALS.equals(operation) || QueryOperation.FIELDNOTEQUALS.equals(operation) || QueryOperation.FIELDGREATERTHAN.equals(operation) || QueryOperation.FIELDLESSTHAN.equals(operation))) { if (value instanceof Collection) { Collection values = (Collection) value; if (Integer.class.equals(type)) { List<Integer> list = new ArrayList<Integer>(); for (Object item : values) { list.add(Integer.parseInt(item.toString())); } value = list; } else if (Long.class.equals(type)) { List<Long> list = new ArrayList<Long>(); for (Object item : values) { list.add(Long.parseLong(item.toString())); } value = list; } else if (java.sql.Date.class.equals(type) || Date.class.equals(type)) { List<Date> list = new ArrayList<Date>(); for (Object item : values) { Tuple<Date, QueryOperation> tuple = convertToDate(item, operation); operation = tuple.getValue(); list.add(tuple.getKey()); } value = list; } else if (Enum.class.isAssignableFrom(type)) { List<Enum> enumValues = new ArrayList<Enum>(values.size()); for (Object item : values) { Enum enumItem = prepareEnumFromSearchCriteria((Class<? extends Enum>) type, item); enumValues.add(enumItem); } value = enumValues; } } else { if (Integer.class.equals(type)) { value = Integer.parseInt(value.toString()); } else if (Long.class.equals(type)) { value = Long.parseLong(value.toString()); } else if (Double.class.equals(type)) { value = Double.parseDouble(value.toString()); } else if (java.sql.Date.class.equals(type) || Date.class.equals(type)) { Tuple<Date, QueryOperation> tuple = convertToDate(value, operation); value = tuple.getKey(); operation = tuple.getValue(); } else if (Enum.class.isAssignableFrom(type)) { value = prepareEnumFromSearchCriteria((Class<? extends Enum>) type, value); } } } if (!String.class.equals(type) && (QueryOperation.LIKECS.equals(operation) || QueryOperation.LIKECSFIRST.equals(operation) || QueryOperation.LIKE.equals(operation) || QueryOperation.LIKEFIRST.equals(operation))) { operation = QueryOperation.EQUALS; } switch (operation) { case LIKECS: criterion = Restrictions.like(query.getField(), "%" + value + "%"); break; case LIKECSFIRST: criterion = Restrictions.like(query.getField(), value + "%"); break; case LIKE: criterion = Restrictions.ilike(query.getField(), "%" + value + "%"); break; case LIKEFIRST: criterion = Restrictions.ilike(query.getField(), value + "%"); break; case EQUALS: criterion = Restrictions.eq(query.getField(), value); break; case LESSTHAN: criterion = Restrictions.lt(query.getField(), value); break; case GREATERTHAN: criterion = Restrictions.gt(query.getField(), value); break; case ISNULL: criterion = Restrictions.isNull(query.getField()); break; case ISNOTNULL: criterion = Restrictions.isNotNull(query.getField()); break; case ISEMPTY: criterion = Restrictions.isEmpty(query.getField()); break; case ISNOTEMPTY: criterion = Restrictions.isNotEmpty(query.getField()); break; case NOTEQUALS: criterion = Restrictions.ne(query.getField(), value); break; case IN: criterion = generateInRestriction(query.getField(), (Collection) value); break; case NOTIN: criterion = Restrictions.not(generateInRestriction(query.getField(), (Collection) value)); break; case FIELDEQUALS: criterion = Restrictions.eqProperty(query.getField(), value != null ? value.toString() : ""); break; case FIELDNOTEQUALS: criterion = Restrictions.neProperty(query.getField(), value != null ? value.toString() : ""); break; case FIELDGREATERTHAN: criterion = Restrictions.gtProperty(query.getField(), value != null ? value.toString() : ""); break; case FIELDLESSTHAN: criterion = Restrictions.ltProperty(query.getField(), value != null ? value.toString() : ""); break; default: throw new RuntimeException("Operation " + query.getField() + " is not a valid operation"); } return criterion; }