Example usage for org.hibernate.criterion Restrictions ne

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

Introduction

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

Prototype

public static SimpleExpression ne(String propertyName, Object value) 

Source Link

Document

Apply a "not equal" constraint to the named property

Usage

From source file:de.cosmocode.hibernate.CustomRestrictions.java

License:Apache License

/**
 * Apply a "not equal" constraint to the named property.
 * /*from   w w w .j  a  va 2s  . c o m*/
 * <p>
 *   Note: This implementation differs from {@link Restrictions#ne(String, Object)}
 *   because it returns {@link CustomRestrictions#isNotEmpty(String)}
 *   in case value is an empty string and returns an logical or expression
 *   of {@link Restrictions#ne(String, Object)} and {@link Restrictions#isNull(String)}.
 * </p>
 * 
 * @param propertyName the name of the property the constraint should be applied to
 * @param value the actual value the property should be not equals to
 * @return a new {@link Criterion}
 */
public static Criterion ne(String propertyName, String value) {
    if (StringUtils.isEmpty(value)) {
        return CustomRestrictions.isNotEmpty(propertyName);
    } else {
        return Restrictions.or(Restrictions.ne(propertyName, value), Restrictions.isNull(propertyName));
    }
}

From source file:de.escidoc.core.aa.business.filter.RoleFilter.java

License:Open Source License

/**
 * Parse the given CQL query and create a corresponding Hibernate query to filter for eSciDoc roles from it.
 *
 * @param query CQL query//from   w  ww.ja  v  a 2s .  c  o m
 * @throws InvalidSearchQueryException thrown if the given search query could not be translated into a SQL query
 */
public RoleFilter(final String query) throws InvalidSearchQueryException {
    //Adding or Removal of values has also to be done in Method evaluate
    //and in the Hibernate-Class-Method retrieveRoles
    //And adapt method ExtendedFilterHandler.transformFilterName
    //URI-style filters/////////////////////////////////////////////////////
    //Filter-Names
    criteriaMap.put(Constants.DC_IDENTIFIER_URI, new Object[] { COMPARE_EQ, "id" });
    criteriaMap.put(TripleStoreUtility.PROP_NAME, new Object[] { COMPARE_LIKE, "roleName" });
    criteriaMap.put(TripleStoreUtility.PROP_CREATED_BY_ID,
            new Object[] { COMPARE_EQ, "userAccountByCreatorId.id" });
    criteriaMap.put(TripleStoreUtility.PROP_MODIFIED_BY_ID,
            new Object[] { COMPARE_EQ, "userAccountByModifiedById.id" });
    criteriaMap.put(TripleStoreUtility.PROP_DESCRIPTION, new Object[] { COMPARE_LIKE, "roleDescription" });
    criteriaMap.put(Constants.PROPERTIES_NS_URI + XmlUtility.NAME_CREATION_DATE,
            new String[] { "r.creationDate = " });

    specialCriteriaNames.add(Constants.PROPERTIES_NS_URI + XmlUtility.NAME_CREATION_DATE);

    //Sortby-Names
    propertyNamesMap.put(TripleStoreUtility.PROP_NAME, "roleName");
    propertyNamesMap.put(TripleStoreUtility.PROP_CREATED_BY_ID, "userAccountByCreatorId.id");
    propertyNamesMap.put(TripleStoreUtility.PROP_MODIFIED_BY_ID, "userAccountByModifiedById.id");
    propertyNamesMap.put(TripleStoreUtility.PROP_DESCRIPTION, "roleDescription");
    propertyNamesMap.put(Constants.DC_IDENTIFIER_URI, "id");
    ////////////////////////////////////////////////////////////////////////

    //Path-style filters/////////////////////////////////////////////////////
    //Filter-Names
    criteriaMap.put(Constants.FILTER_PATH_ID, new Object[] { COMPARE_EQ, "id" });
    criteriaMap.put(Constants.FILTER_PATH_NAME, new Object[] { COMPARE_LIKE, "roleName" });
    criteriaMap.put(Constants.FILTER_PATH_CREATED_BY_ID,
            new Object[] { COMPARE_EQ, "userAccountByCreatorId.id" });
    criteriaMap.put(Constants.FILTER_PATH_MODIFIED_BY_ID,
            new Object[] { COMPARE_EQ, "userAccountByModifiedById.id" });
    criteriaMap.put(Constants.FILTER_PATH_DESCRIPTION, new Object[] { COMPARE_LIKE, "roleDescription" });
    criteriaMap.put(Constants.FILTER_PATH_CREATION_DATE, new String[] { "r.creationDate = " });
    criteriaMap.put("limited", new Object[] {});
    criteriaMap.put("granted", new Object[] {});

    specialCriteriaNames.add(Constants.FILTER_PATH_CREATION_DATE);
    specialCriteriaNames.add("limited");
    specialCriteriaNames.add("granted");

    //Sortby-Names
    propertyNamesMap.put(Constants.FILTER_PATH_ID, "id");
    propertyNamesMap.put(Constants.FILTER_PATH_NAME, "roleName");
    propertyNamesMap.put(Constants.FILTER_PATH_CREATED_BY_ID, "userAccountByCreatorId.id");
    propertyNamesMap.put(Constants.FILTER_PATH_MODIFIED_BY_ID, "userAccountByModifiedById.id");
    propertyNamesMap.put(Constants.FILTER_PATH_DESCRIPTION, "roleDescription");
    ////////////////////////////////////////////////////////////////////////

    if (query != null) {
        try {
            final CQLParser parser = new CQLParser();

            this.detachedCriteria = DetachedCriteria.forClass(EscidocRole.class, "r");
            detachedCriteria.add(Restrictions.ne("id", EscidocRole.DEFAULT_USER_ROLE_ID));

            final Criterion criterion = evaluate(parser.parse(query));

            if (criterion != null) {
                detachedCriteria.add(criterion);
            }
        } catch (final Exception e) {
            throw new InvalidSearchQueryException(e);
        }
    }
}

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)
 *///w ww  .  ja v a  2s.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.escidoc.core.aa.business.persistence.hibernate.HibernateEscidocRoleDao.java

License:Open Source License

/**
 * See Interface for functional description.
 *
 * @see EscidocRoleDaoInterface #retrieveRoles(java.lang.String, int, int)
 *///w  w w  .jav  a  2  s  .c om
@Override
public List<EscidocRole> retrieveRoles(final String criterias, final int offset, final int maxResults)
        throws InvalidSearchQueryException, SqlDatabaseSystemException {

    final List<EscidocRole> result;

    if (criterias != null && criterias.length() > 0) {
        result = getHibernateTemplate().findByCriteria(new RoleFilter(criterias).toSql(), offset, maxResults);
    } else {
        try {
            final DetachedCriteria detachedCriteria = DetachedCriteria.forClass(EscidocRole.class, "r");

            detachedCriteria.add(Restrictions.ne("id", EscidocRole.DEFAULT_USER_ROLE_ID));
            result = getHibernateTemplate().findByCriteria(detachedCriteria, offset, maxResults);
        } catch (final DataAccessException e) {
            throw new SqlDatabaseSystemException(e);
        }
    }
    return result;
}

From source file:de.escidoc.core.common.business.filter.CqlFilter.java

License:Open Source License

/**
 * Evaluate a CQL relation./*w  w w  .  j  a  v  a  2  s . co m*/
 * 
 * @param relation
 *            CQL relation
 * @param propertyName
 *            left side of the statement
 * @param value
 *            right side of the statement
 * @param useLike
 *            use LIKE instead of = in case of an equality relation
 * @return Hibernate query reflecting the given CQL query
 * @throws InvalidSearchQueryException
 *             thrown if the given search query could not be translated into a SQL query
 */
protected Criterion evaluate(final CQLRelation relation, final String propertyName, final Object value,
        final boolean useLike) throws InvalidSearchQueryException {
    final Criterion result;
    final String rel = relation.getBase();

    if (value == null || value.toString().length() == 0) {
        result = Restrictions.isNull(propertyName);
    } else {
        if ("<".equals(rel)) {
            result = Restrictions.lt(propertyName, value);
        } else if ("<=".equals(rel)) {
            result = Restrictions.le(propertyName, value);
        } else if ("=".equals(rel)) {
            result = useLike ? Restrictions.like(propertyName, value) : Restrictions.eq(propertyName, value);
        } else if (">=".equals(rel)) {
            result = Restrictions.ge(propertyName, value);
        } else if (">".equals(rel)) {
            result = Restrictions.gt(propertyName, value);
        } else if ("<>".equals(rel)) {
            result = Restrictions.ne(propertyName, value);
        } else {
            throw new InvalidSearchQueryException(rel + ": relation not implemented");
        }
    }
    return result;
}

From source file:de.ingrid.portal.forms.AdminContentPartnerForm.java

License:EUPL

/**
 * @see de.ingrid.portal.forms.ActionForm#validate()
 *///w w w  . j  a v a  2  s . c o m
public boolean validate() {
    boolean allOk = true;
    clearErrors();

    // check input
    try {
        String numEntities = getInput("numEntities");
        if (numEntities != null) {
            int intNumEntities = new Integer(numEntities).intValue();
            String fieldName = "";
            ArrayList newIdents = new ArrayList(intNumEntities);
            for (int i = 0; i < intNumEntities; i++) {

                // IDENT
                fieldName = FIELD_IDENT + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "content.partner.edit.error.noIdent");
                    allOk = false;
                } else {
                    String ident = getInput(fieldName);
                    // check whether we add multiple new records where new idents are the same !
                    if (newIdents.contains(ident)) {
                        setError(fieldName, "content.partner.edit.error.doubleIdent");
                        allOk = false;
                    } else {
                        newIdents.add(ident);
                        // check database whether other record (other id) has same ident (kuerzel)
                        Long id = null;
                        try {
                            id = new Long(getInput(PARAM_ID + i));
                        } catch (Exception ex) {
                        }
                        Session session = HibernateUtil.currentSession();
                        Criteria crit = session.createCriteria(IngridPartner.class)
                                .add(Restrictions.eq(FIELD_IDENT, ident));
                        if (id != null) {
                            crit.add(Restrictions.ne(PARAM_ID, id));
                        }
                        List foundPartners = UtilsDB.getValuesFromDB(crit, session, null, true);
                        if (!foundPartners.isEmpty()) {
                            setError(fieldName, "content.partner.edit.error.doubleIdent");
                            allOk = false;
                        }
                    }
                }

                // NAME
                fieldName = FIELD_NAME + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "content.partner.edit.error.noName");
                    allOk = false;
                }
            }
        }
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            log.error("Error validating input.", t);
        }
        allOk = false;
    } finally {
        HibernateUtil.closeSession();
    }

    return allOk;
}

From source file:de.ingrid.portal.forms.AdminContentProviderForm.java

License:EUPL

/**
 * @see de.ingrid.portal.forms.ActionForm#validate()
 *///from  w  w  w  . j a v  a 2 s.  c  om
public boolean validate() {
    boolean allOk = true;
    clearErrors();

    // check input
    try {
        String numEntities = getInput("numEntities");
        if (numEntities != null) {
            int intNumEntities = new Integer(numEntities).intValue();
            String fieldName = "";
            ArrayList newIdents = new ArrayList(intNumEntities);
            for (int i = 0; i < intNumEntities; i++) {

                // IDENT
                fieldName = FIELD_IDENT + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "content.provider.edit.error.noIdent");
                    allOk = false;
                } else {
                    String ident = getInput(fieldName);
                    // check whether we add multiple new records where new idents are the same !
                    if (newIdents.contains(ident)) {
                        setError(fieldName, "content.provider.edit.error.doubleIdent");
                        allOk = false;
                    } else {
                        newIdents.add(ident);
                        // check database whether other record (other id) has same ident (kuerzel)
                        Long id = null;
                        try {
                            id = new Long(getInput(PARAM_ID + i));
                        } catch (Exception ex) {
                        }
                        Session session = HibernateUtil.currentSession();
                        Criteria crit = session.createCriteria(IngridProvider.class)
                                .add(Restrictions.eq(FIELD_IDENT, ident));
                        if (id != null) {
                            crit.add(Restrictions.ne(PARAM_ID, id));
                        }
                        List foundProviders = UtilsDB.getValuesFromDB(crit, session, null, true);
                        if (!foundProviders.isEmpty()) {
                            setError(fieldName, "content.provider.edit.error.doubleIdent");
                            allOk = false;
                        }
                    }
                }

                // NAME
                fieldName = FIELD_NAME + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "content.provider.edit.error.noName");
                    allOk = false;
                }
            }
        }
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            log.error("Error validating input.", t);
        }
        allOk = false;
    } finally {
        HibernateUtil.closeSession();
    }

    return allOk;
}

From source file:de.ingrid.portal.forms.AdminRSSForm.java

License:EUPL

/**
 * @see de.ingrid.portal.forms.ActionForm#validate()
 *//* www . j a  v  a2s .  c  o m*/
public boolean validate() {
    boolean allOk = true;
    clearErrors();

    // check input
    try {
        String numEntities = getInput("numEntities");
        if (numEntities != null) {
            int intNumEntities = new Integer(numEntities).intValue();
            String fieldName = "";
            for (int i = 0; i < intNumEntities; i++) {

                fieldName = FIELD_DESCRIPTION + i;
                if (hasInput(fieldName)) {
                    if (getInput(fieldName).length() > 1024)
                        setError(fieldName, "admin.rss.error.description.too.long");
                    allOk = false;
                }

                fieldName = FIELD_PROVIDER + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "admin.rss.error.missing.provider");
                    allOk = false;
                }
                fieldName = FIELD_URL + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "admin.rss.error.missing.url");
                    allOk = false;
                } else {
                    // check database whether other record (other id) has
                    // same ident (kuerzel)
                    Long id = null;
                    try {
                        id = new Long(getInput(PARAM_ID + i));
                    } catch (Exception ex) {
                    }
                    String url = getInput(fieldName);
                    Session session = HibernateUtil.currentSession();
                    Criteria crit = session.createCriteria(IngridRSSSource.class)
                            .add(Restrictions.eq(FIELD_URL, url));
                    if (id != null) {
                        crit.add(Restrictions.ne(PARAM_ID, id));
                    }
                    List foundURLs = UtilsDB.getValuesFromDB(crit, session, null, true);
                    if (foundURLs != null && !foundURLs.isEmpty()) {
                        setError(fieldName, "admin.rss.error.url.exists");
                        allOk = false;
                    }
                }
                fieldName = FIELD_LANGUAGE + i;
                if (!hasInput(fieldName)) {
                    setError(fieldName, "admin.rss.error.missing.language");
                    allOk = false;
                }
            }
        }
    } catch (Throwable t) {
        if (log.isErrorEnabled()) {
            log.error("Error validating input.", t);
        }
        allOk = false;
    } finally {
        HibernateUtil.closeSession();
    }

    return allOk;
}

From source file:de.iteratec.iteraplan.businesslogic.reports.query.node.AbstractLeafNode.java

License:Open Source License

/**
 * Returns the {@link Criterion} for the specified {@code effectivePropertyName} and {@code comparator}.
 * /*from   w w w  .j a  v  a 2  s  .com*/
 * @param effectivePropertyName the property name path
 * @param comparator the comparator describing the compare operation
 * @param attrType string representation of the property's attribute type as in {@link BBAttribute#getTypeOfAttribute(String)} 
 * @return the newly created {@link Criterion} for the specified {@code comparator} or {@code null} if the 
 *    comparator is not supported
 */
protected Criterion getCriterionForComparator(String effectivePropertyName, Comparator comparator,
        String attrType) {
    Criterion criterion = null;
    switch (comparator) {
    case EQ:
        criterion = Restrictions.eq(effectivePropertyName, getProcessedPattern());
        break;
    case GEQ:
        criterion = Restrictions.ge(effectivePropertyName, getProcessedPattern());
        break;
    case LEQ:
        criterion = Restrictions.le(effectivePropertyName, getProcessedPattern());
        break;
    case GT:
        criterion = Restrictions.gt(effectivePropertyName, getProcessedPattern());
        break;
    case LT:
        criterion = Restrictions.lt(effectivePropertyName, getProcessedPattern());
        break;
    case LIKE:
        criterion = new IteraplanLikeExpression(effectivePropertyName, getProcessedPattern().toString(), true);
        break;
    case NOT_LIKE:
        criterion = Restrictions.not(
                new IteraplanLikeExpression(effectivePropertyName, getProcessedPattern().toString(), true));
        break;
    case IS:
        // see Type#getSpecialPropertyHQLStrings
        criterion = "null".equals(getPattern()) ? Restrictions.isNull(effectivePropertyName)
                : Restrictions.isNotNull(effectivePropertyName);
        break;
    case ANY_ASSIGNMENT:
        criterion = getAnyAssignmentCriterion(effectivePropertyName, attrType);
        break;
    case NO_ASSIGNMENT:
        criterion = getNoAssignmentCriterion(effectivePropertyName, attrType);
        break;
    case NEQ:
        criterion = Restrictions.ne(effectivePropertyName, getProcessedPattern());
        break;
    default:
        break;
    }

    return criterion;
}

From source file:de.iteratec.iteraplan.persistence.dao.GenericBaseDAO.java

License:Open Source License

/** {@inheritDoc} */
public boolean doesObjectWithDifferentIdExist(final T identifier, final String name) {
    Assert.notNull(name);// w  w w . j a va2 s.  c  om

    HibernateCallback<Long> callback = new HibernateCallback<Long>() {
        public Long doInHibernate(Session session) {
            Criteria c = session.createCriteria(getPersistentClass());
            c.setProjection(Projections.count(getNameAttribute()));
            c.add(Restrictions.eq(getNameAttribute(), name.trim()).ignoreCase());
            if (identifier != null) {
                c.add(Restrictions.ne("id", identifier));
            }
            Object result = c.uniqueResult();

            // if Hibernate returns an Integer, convert it to long
            if (result instanceof Integer) {
                return Long.valueOf(((Integer) result).longValue());
            }
            // otherwise we expect a Long to be returned
            return (Long) result;
        }
    };

    Long count = getHibernateTemplate().execute(callback);

    return count.intValue() > 0 ? true : false;
}