Example usage for org.hibernate.criterion Restrictions isNotNull

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

Introduction

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

Prototype

public static Criterion isNotNull(String propertyName) 

Source Link

Document

Apply an "is not null" constraint to the named property

Usage

From source file:gov.nih.nci.firebird.service.protocol.FormTypeServiceBean.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
// Hibernate list() method is untyped
public List<FormType> getSupplementalForms(RegistrationType registrationType) {
    List<FormType> allSupplementalForms = getSession().createCriteria(FormType.class)
            .add(Restrictions.isNotNull(FORM_TYPE_ENUM_PROP))
            .add(Restrictions.or(Restrictions.eq(INV_OPTIONALITY_ENUM_PROP, FormOptionality.SUPPLEMENTARY),
                    Restrictions.eq(SUBINV_OPTIONALITY_ENUM_PROP, FormOptionality.SUPPLEMENTARY)))
            .list();//from w  ww .  ja  va2 s  .  com
    filterByType(allSupplementalForms, registrationType);
    return allSupplementalForms;
}

From source file:gr.abiss.calipso.hibernate.HibernateDao.java

License:Open Source License

@Override
public int loadCountOfRecordsHavingFieldNotNull(Space space, Field field) {
    Criteria criteria = getSession().createCriteria(Item.class);
    criteria.add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    int itemCount = NumberUtils.toInt(criteria.list().get(0).toString());
    // even when no item has this field not null currently, items may have history with this field not null
    // because of the "parent" difference, cannot use AbstractItem and have to do a separate Criteria query
    criteria = getSession().createCriteria(History.class);
    criteria.createCriteria("parent").add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    return itemCount + NumberUtils.toInt(criteria.list().get(0).toString());
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

public org.grails.datastore.mapping.query.api.Criteria isNotNull(String property) {
    String propertyName = calculatePropertyName(property);
    addToCriteria(Restrictions.isNotNull(propertyName));
    return this;
}

From source file:grails.orm.HibernateCriteriaBuilder.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override//from   w ww .j  a va2 s.  c  o  m
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:hibernate.HibernateConstantEntities.java

License:Open Source License

/**
 * Check all URL`s containing a versionInfo, which represents an OntologyURL
 * Put into ontologyVersionsMap the versionInfo and the databaseID 
 *//*from ww  w . j a v  a 2s.  c  om*/
public void checkOntologyVersionField() {
    Url ontologyURL = null;

    Session hibernateSession = DatabaseFacade.getSingletonFacade().getHibernateSession();

    Criteria crit = hibernateSession.createCriteria(Url.class);
    crit.add(Restrictions.isNotNull("versionInfo"));
    List<Url> urlList = crit.list();

    if (!urlList.isEmpty()) {

        ontologyURL = urlList.get(0);

        String versionInfo = ontologyURL.getVersionInfo();
        long urlId = ontologyURL.getId();
        ontologyVersionsMap.put(versionInfo, urlId);
        log.debug("Selected ontology with Versioninfo " + versionInfo + " in database with ID: "
                + ontologyURL.getId());

    } else {
        log.debug("Ontology Documentversion with Type \"Ontology\" not exists. Resullist is empty.");
    }
}

From source file:info.jtrac.hibernate.HibernateJtracDao.java

License:Apache License

public int loadCountOfRecordsHavingFieldNotNull(Space space, Field field) {
    Criteria criteria = getSession().createCriteria(Item.class);
    criteria.add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    int itemCount = (Integer) criteria.list().get(0);
    // even when no item has this field not null currently, items may have history with this field not null
    // because of the "parent" difference, cannot use AbstractItem and have to do a separate Criteria query
    criteria = getSession().createCriteria(History.class);
    criteria.createCriteria("parent").add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    return itemCount + (Integer) criteria.list().get(0);
}

From source file:info.jtrac.repository.HibernateJtracDao.java

License:Apache License

@Override
@Transactional(propagation = Propagation.SUPPORTS)
public int loadCountOfRecordsHavingFieldNotNull(Space space, Field field) {
    Criteria criteria = getSession().createCriteria(Item.class);
    criteria.add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    int itemCount = (Integer) criteria.list().get(0);
    // even when no item has this field not null currently, items may have history with this field not null
    // because of the "parent" difference, cannot use AbstractItem and have to do a separate Criteria query
    criteria = getSession().createCriteria(History.class);
    criteria.createCriteria("parent").add(Restrictions.eq("space", space));
    criteria.add(Restrictions.isNotNull(field.getName().toString()));
    criteria.setProjection(Projections.rowCount());
    return itemCount + (Integer) criteria.list().get(0);
}

From source file:interfaces.Alta.java

private int maxIdCliente() {
    Session session;/*from   w ww  .  j av a2s .c  o  m*/
    session = ConexionUtil.getSessionFactory().openSession();
    Criteria criteria = session.createCriteria(Cliente.class);
    criteria.add(Restrictions.isNotNull("idCliente"));
    criteria.setProjection(Projections.projectionList().add(Projections.max("idCliente")));

    if (criteria.list().get(0) != null) {
        return (int) criteria.list().get(0) + 1;
    } else
        return 1;
}

From source file:it.av.es.service.impl.OrderServiceHibernate.java

License:Apache License

private int getLastInvoiceNumber(Project project, Date invoiceDate) {
    Criteria criteria = getHibernateSession().createCriteria(getPersistentClass());
    criteria.add(Restrictions.sqlRestriction("date_trunc('year', this_.creation_time) = '"
            + DateUtil.SDF2SIMPLEUSA.print(DateUtils.truncate(invoiceDate, Calendar.YEAR).getTime()) + "'"));
    criteria.add(Restrictions.isNotNull("invoiceNumber"));
    criteria.addOrder(org.hibernate.criterion.Order.desc("invoiceNumber"));
    List<Order> list = criteria.list();
    int lastInvoiceNumber = 0;
    if (list.size() > 0) {
        lastInvoiceNumber = list.get(0).getInvoiceNumber();
    }/* ww w .j  a v a  2 s .com*/
    return lastInvoiceNumber;
}

From source file:kltn.dao.AreaDAO.java

public List<Area> findByBoudaryNull() {
    Session session = HibernateUtil.getSessionFactory().openSession();
    List<Area> list = null;
    Transaction tx = null;/*from ww w. j  a va2s .  c om*/
    try {

        tx = session.beginTransaction();
        Criteria cr = session.createCriteria(Area.class);
        cr.add(Restrictions.isNotNull("bound"));
        list = cr.list();
        tx.commit();
    } catch (HibernateException he) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
    }
    return list;
}