Example usage for org.hibernate.criterion Restrictions or

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

Introduction

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

Prototype

public static LogicalExpression or(Criterion lhs, Criterion rhs) 

Source Link

Document

Return the disjuction of two expressions

Usage

From source file:gov.nih.nci.cananolab.service.sample.helper.SampleServiceHelper.java

License:BSD License

public List<Sample> findSamplesBy(String sampleName, String samplePointOfContact,
        String[] nanomaterialEntityClassNames, String[] otherNanomaterialEntityTypes,
        String[] functionalizingEntityClassNames, String[] otherFunctionalizingEntityTypes,
        String[] functionClassNames, String[] otherFunctionTypes, String[] characterizationClassNames,
        String[] otherCharacterizationTypes, String[] wordList) throws Exception {
    List<String> sampleIds = new ArrayList<String>();

    //logger.error("Processing: " + sampleName);

    // can't query for the entire Sample object due to
    // limitations in pagination in SDK

    // added createdDate and sample name in the results so data can be
    // sorted by date and name
    DetachedCriteria crit = DetachedCriteria.forClass(Sample.class);
    //            .setProjection(
    //                  Projections.projectionList()
    //                        .add(Projections.property("id"))
    //                        .add(Projections.property("name"))
    //                        .add(Projections.property("createdDate")));
    if (!StringUtils.isEmpty(sampleName)) {
        TextMatchMode nameMatchMode = new TextMatchMode(sampleName);
        crit.add(Restrictions.ilike("name", nameMatchMode.getUpdatedText(), nameMatchMode.getMatchMode()));
    }//from  w w  w  . ja  va  2 s  .c  o m
    if (!StringUtils.isEmpty(samplePointOfContact)) {
        TextMatchMode pocMatchMode = new TextMatchMode(samplePointOfContact);
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("primaryPointOfContact", "pointOfContact");
        crit.createAlias("pointOfContact.organization", "organization");
        crit.createAlias("otherPointOfContactCollection", "otherPoc", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("otherPoc.organization", "otherOrg", CriteriaSpecification.LEFT_JOIN);
        String[] critStrs = { "pointOfContact.lastName", "pointOfContact.firstName", "pointOfContact.role",
                "organization.name", "otherPoc.lastName", "otherPoc.firstName", "otherOrg.name" };
        for (String critStr : critStrs) {
            Criterion pocCrit = Restrictions.ilike(critStr, pocMatchMode.getUpdatedText(),
                    pocMatchMode.getMatchMode());
            disjunction.add(pocCrit);
        }
        crit.add(disjunction);
    }

    // join composition
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0
            || functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
        crit.createAlias("sampleComposition", "comp", CriteriaSpecification.LEFT_JOIN);
    }
    // join nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.nanomaterialEntityCollection", "nanoEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // join functionalizing entity
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        crit.createAlias("comp.functionalizingEntityCollection", "funcEntity", CriteriaSpecification.LEFT_JOIN);
    }

    // nanomaterial entity
    if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0
            || otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (nanomaterialEntityClassNames != null && nanomaterialEntityClassNames.length > 0) {
            Criterion nanoEntityCrit = Restrictions.in("nanoEntity.class", nanomaterialEntityClassNames);
            disjunction.add(nanoEntityCrit);
        }
        if (otherNanomaterialEntityTypes != null && otherNanomaterialEntityTypes.length > 0) {
            Criterion otherNanoCrit1 = Restrictions.eq("nanoEntity.class", "OtherNanomaterialEntity");
            Criterion otherNanoCrit2 = Restrictions.in("nanoEntity.type", otherNanomaterialEntityTypes);
            Criterion otherNanoCrit = Restrictions.and(otherNanoCrit1, otherNanoCrit2);
            disjunction.add(otherNanoCrit);
        }
        crit.add(disjunction);
    }

    // functionalizing entity
    // need to turn class names into integers in order for the .class
    // clause to work
    if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0
            || otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0
            || functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (functionalizingEntityClassNames != null && functionalizingEntityClassNames.length > 0) {
            Integer[] functionalizingEntityClassNameIntegers = this
                    .convertToFunctionalizingEntityClassOrderNumber(functionalizingEntityClassNames);
            Criterion funcEntityCrit = Restrictions.in("funcEntity.class",
                    functionalizingEntityClassNameIntegers);
            disjunction.add(funcEntityCrit);
        }
        if (otherFunctionalizingEntityTypes != null && otherFunctionalizingEntityTypes.length > 0) {
            Integer classOrderNumber = Constants.FUNCTIONALIZING_ENTITY_SUBCLASS_ORDER_MAP
                    .get("OtherFunctionalizingEntity");
            Criterion otherFuncCrit1 = Restrictions.eq("funcEntity.class", classOrderNumber);
            Criterion otherFuncCrit2 = Restrictions.in("funcEntity.type", otherFunctionalizingEntityTypes);
            Criterion otherFuncCrit = Restrictions.and(otherFuncCrit1, otherFuncCrit2);
            disjunction.add(otherFuncCrit);
        }
        crit.add(disjunction);
    }

    // function
    if (functionClassNames != null && functionClassNames.length > 0
            || otherFunctionTypes != null && otherFunctionTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        crit.createAlias("nanoEntity.composingElementCollection", "compElement",
                CriteriaSpecification.LEFT_JOIN).createAlias("compElement.inherentFunctionCollection", "inFunc",
                        CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("funcEntity.functionCollection", "func", CriteriaSpecification.LEFT_JOIN);
        if (functionClassNames != null && functionClassNames.length > 0) {
            Criterion funcCrit1 = Restrictions.in("inFunc.class", functionClassNames);
            Criterion funcCrit2 = Restrictions.in("func.class", functionClassNames);
            disjunction.add(funcCrit1).add(funcCrit2);
        }
        if (otherFunctionTypes != null && otherFunctionTypes.length > 0) {
            Criterion otherFuncCrit1 = Restrictions.and(Restrictions.eq("inFunc.class", "OtherFunction"),
                    Restrictions.in("inFunc.type", otherFunctionTypes));
            Criterion otherFuncCrit2 = Restrictions.and(Restrictions.eq("func.class", "OtherFunction"),
                    Restrictions.in("func.type", otherFunctionTypes));
            disjunction.add(otherFuncCrit1).add(otherFuncCrit2);
        }
        crit.add(disjunction);
    }

    // join characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0
            || wordList != null && wordList.length > 0) {
        crit.createAlias("characterizationCollection", "chara", CriteriaSpecification.LEFT_JOIN);
    }
    // characterization
    if (characterizationClassNames != null && characterizationClassNames.length > 0
            || otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        if (characterizationClassNames != null && characterizationClassNames.length > 0) {
            Criterion charCrit = Restrictions.in("chara.class", characterizationClassNames);
            disjunction.add(charCrit);
        }
        if (otherCharacterizationTypes != null && otherCharacterizationTypes.length > 0) {
            Criterion otherCharCrit1 = Restrictions.eq("chara.class", "OtherCharacterization");
            Criterion otherCharCrit2 = Restrictions.in("chara.name", otherCharacterizationTypes);
            Criterion otherCharCrit = Restrictions.and(otherCharCrit1, otherCharCrit2);
            disjunction.add(otherCharCrit);
        }
        crit.add(disjunction);
    }
    // join keyword, finding, publication
    if (wordList != null && wordList.length > 0) {
        crit.createAlias("keywordCollection", "keyword1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("chara.findingCollection", "finding", CriteriaSpecification.LEFT_JOIN)
                .createAlias("finding.fileCollection", "charFile", CriteriaSpecification.LEFT_JOIN)
                .createAlias("charFile.keywordCollection", "keyword2", CriteriaSpecification.LEFT_JOIN);
        // publication keywords
        crit.createAlias("publicationCollection", "pub1", CriteriaSpecification.LEFT_JOIN);
        crit.createAlias("pub1.keywordCollection", "keyword3", CriteriaSpecification.LEFT_JOIN);
    }

    // keyword
    if (wordList != null && wordList.length > 0) {
        Disjunction disjunction = Restrictions.disjunction();
        for (String keyword : wordList) {
            // strip wildcards from either ends of keyword
            keyword = StringUtils.stripWildcards(keyword);
            Criterion keywordCrit1 = Restrictions.ilike("keyword1.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit2 = Restrictions.ilike("keyword2.name", keyword, MatchMode.ANYWHERE);
            Criterion keywordCrit3 = Restrictions.ilike("keyword3.name", keyword, MatchMode.ANYWHERE);
            disjunction.add(keywordCrit1);
            disjunction.add(keywordCrit2);
            disjunction.add(keywordCrit3);
        }
        for (String word : wordList) {
            Criterion summaryCrit1 = Restrictions.ilike("chara.designMethodsDescription", word,
                    MatchMode.ANYWHERE);
            Criterion summaryCrit2 = Restrictions.ilike("charFile.description", word, MatchMode.ANYWHERE);
            Criterion summaryCrit = Restrictions.or(summaryCrit1, summaryCrit2);
            disjunction.add(summaryCrit);
        }
        crit.add(disjunction);
    }

    CaNanoLabApplicationService appService = (CaNanoLabApplicationService) ApplicationServiceProvider
            .getApplicationService();

    List results = appService.query(crit);
    List<Sample> samples = new ArrayList<Sample>();
    //      List<String> accessibleData = getAccessibleData();
    for (int i = 0; i < results.size(); i++) {

        try {
            Sample sample = (Sample) results.get(i);
            System.out.println("sample ID test === " + sample.getId());
            samples.add(sample);
        } catch (ClassCastException e) {
            logger.error("Got ClassCastException: " + e.getMessage());
            break;
        }
    }

    List<Sample> orderedSamples = new ArrayList<Sample>(samples);
    // Collections.sort(orderedSamples,
    // Collections.reverseOrder(new Comparators.SampleDateComparator()));

    Collections.sort(orderedSamples, new Comparators.SampleDateComparator());

    for (Sample sample : orderedSamples) {
        sampleIds.add(sample.getId().toString());
    }

    return samples;
}

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 w w.j av  a  2 s  . c o  m*/
    filterByType(allSupplementalForms, registrationType);
    return allSupplementalForms;
}

From source file:gov.nih.nci.system.web.AutoCompletionService.java

License:BSD License

/**
 * Returns a list of Keywords in which any word begins with the given input 
 * string./* w  w  w. j av a2  s.com*/
 * @param s Prefix for auto-completion suggestion
 * @return List of Keyword objects matching the input string
 * @throws ApplicationException
 */
public List<Keyword> getKeywords(String s) throws ApplicationException {

    List<Keyword> results = null;
    Session session = null;

    String lwrs = s.toLowerCase();

    try {
        session = sessionFactory.openSession();
        Criteria c = session.createCriteria(Keyword.class);
        c = c.add(Restrictions.or(new EscapingLikeExpression("value", escape(lwrs) + "%"),
                new EscapingLikeExpression("value", "% " + escape(lwrs) + "%")));
        c = c.addOrder(Order.desc("score"));

        c.setMaxResults(10);
        results = c.list();
    } finally {
        session.close();
    }

    return results;
}

From source file:ispyb.server.common.daos.config.Menu3DAOBean.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Menu3VO> findFiltered(Integer parentId, Integer menuGroupId, String proposalType) {
    entityManager = entitymanagerFactory.createEntityManager();
    try {//from w w w  .jav  a2s  .c o m
        Session session = (Session) entityManager.getDelegate();

        Criteria criteriaMenu = session.createCriteria(Menu3VO.class);
        Criteria criteriaMenuGroup = criteriaMenu.createCriteria("menuGroupVOs");

        criteriaMenu.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // DISTINCT RESULTS !

        if (proposalType != null) {
            criteriaMenu.add(Restrictions.or(Restrictions.eq("expType", "MB"),
                    Restrictions.eq("expType", proposalType)));
        }

        if (menuGroupId != null) {
            criteriaMenuGroup.add(Restrictions.eq("menuGroupId", menuGroupId));
        }

        if (parentId != null) {
            criteriaMenu.add(Restrictions.eq("parentId", parentId));
        }
        criteriaMenu.addOrder(Order.asc("parentId"));
        criteriaMenu.addOrder(Order.asc("sequence"));

        return criteriaMenu.list();
    } finally {
        entityManager.close();
    }
}

From source file:ispyb.server.common.services.config.Menu3ServiceBean.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from  ww  w .j av a2  s .  c o m*/
public List<Menu3VO> findFiltered(final Integer parentId, final Integer menuGroupId, final String proposalCode)
        throws Exception {

    entityManager = entitymanagerFactory.createEntityManager();
    try {
        Session session = (Session) entityManager.getDelegate();

        Criteria criteriaMenu = session.createCriteria(Menu3VO.class);
        Criteria criteriaMenuGroup = criteriaMenu.createCriteria("menuGroupVOs");

        criteriaMenu.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // DISTINCT RESULTS !

        if (proposalCode != null) {
            criteriaMenu.add(Restrictions.or(Restrictions.eq("expType", "MB"),
                    Restrictions.eq("expType", proposalCode)));
        }

        if (menuGroupId != null) {
            criteriaMenuGroup.add(Restrictions.eq("menuGroupId", menuGroupId));
        }

        if (parentId != null) {
            criteriaMenu.add(Restrictions.eq("parentId", parentId));
        }
        criteriaMenu.addOrder(Order.asc("parentId"));
        criteriaMenu.addOrder(Order.asc("sequence"));

        List<Menu3VO> vos = getMenu3VOs(criteriaMenu.list());
        return vos;

    } finally {
        entityManager.close();
    }
}

From source file:it.av.eatt.service.impl.EaterServiceHibernate.java

License:Apache License

/**
 * {@inheritDoc}/*w  w w  . j av  a 2 s.c o m*/
 */
@Override
public Collection<Eater> findUserWithoutRelation(Eater forUser, String pattern) {
    // TODO can be improved with an outer join
    Collection<EaterRelation> relatedUser = userRelationService.getAllRelations(forUser);
    ArrayList<String> relatedUserId = new ArrayList<String>(relatedUser.size());
    for (EaterRelation userRelation : relatedUser) {
        relatedUserId.add(userRelation.getToUser().getId());
    }
    List<Criterion> criterions = new ArrayList<Criterion>(3);
    if (StringUtils.isNotBlank(pattern)) {
        criterions.add(Restrictions.or(Restrictions.ilike(Eater.FIRSTNAME, pattern),
                Restrictions.ilike(Eater.LASTNAME, pattern)));
    }
    if (relatedUserId.size() > 0) {
        criterions.add(Restrictions.not(Restrictions.in(Eater.ID, relatedUserId)));
    }
    // escludes the forUser from the search
    criterions.add(Restrictions.not(Restrictions.idEq(forUser.getId())));
    List<Eater> results = super.findByCriteria(criterions.toArray(new Criterion[criterions.size()]));
    return results;
}

From source file:it.jugpadova.blo.EventBo.java

License:Apache License

public List<Event> search(EventSearch eventSearch) {
    List<Event> events = new LinkedList<Event>();
    try {/*from  w  w w . j  ava 2s  . c om*/
        DetachedCriteria eventCriteria = DetachedCriteria.forClass(Event.class);
        if (StringUtils.isNotBlank(eventSearch.getJugName())
                || StringUtils.isNotBlank(eventSearch.getFriendlyName())
                || StringUtils.isNotBlank(eventSearch.getCountry())
                || StringUtils.isNotBlank(eventSearch.getContinent())) {
            DetachedCriteria ownerCriteria = eventCriteria.createCriteria("owner.jug");
            if (StringUtils.isNotBlank(eventSearch.getJugName())) {
                ownerCriteria.add(Restrictions.ilike("name", eventSearch.getJugName(), MatchMode.ANYWHERE));
            }
            if (StringUtils.isNotBlank(eventSearch.getFriendlyName())) {
                ownerCriteria.add(Restrictions.or(Restrictions.eq("name", eventSearch.getFriendlyName()),
                        Restrictions.eq("internalFriendlyName", eventSearch.getFriendlyName())));
            }
            if (StringUtils.isNotBlank(eventSearch.getCountry())
                    || StringUtils.isNotBlank(eventSearch.getContinent())) {
                DetachedCriteria countryCriteria = ownerCriteria.createCriteria("country");
                if (StringUtils.isNotBlank(eventSearch.getCountry())) {
                    countryCriteria.add(Restrictions.or(
                            Restrictions.ilike("englishName", eventSearch.getCountry(), MatchMode.ANYWHERE),
                            Restrictions.ilike("localName", eventSearch.getCountry(), MatchMode.ANYWHERE)));
                }
                if (StringUtils.isNotBlank(eventSearch.getContinent())) {
                    DetachedCriteria continentCriteria = countryCriteria.createCriteria("continent");
                    continentCriteria
                            .add(Restrictions.ilike("name", eventSearch.getContinent(), MatchMode.ANYWHERE));
                }
            }
        }
        if (!eventSearch.isPastEvents()) {
            eventCriteria.add(Restrictions.ge("startDate", new Date()));
        }
        if (eventSearch.getStartDate() != null) {
            eventCriteria.add(Restrictions.ge("startDate", eventSearch.getStartDate()));
        }
        if (eventSearch.getEndDate() != null) {
            eventCriteria.add(Restrictions.le("endDate", eventSearch.getEndDate()));
        }
        if ("desc".equals(eventSearch.getOrderByDate())) {
            eventCriteria.addOrder(Order.desc("startDate"));
            eventCriteria.addOrder(Order.desc("creationDate"));
        } else {
            eventCriteria.addOrder(Order.asc("startDate"));
            eventCriteria.addOrder(Order.asc("creationDate"));
        }
        if (eventSearch.getMaxResults() == null) {
            events = eventDao.searchByCriteria(eventCriteria);
        } else {
            events = eventDao.searchByCriteria(eventCriteria, 0, eventSearch.getMaxResults().intValue());
        }
        for (Event event : events) {
            event.getParticipants().size();
        }
    } catch (Exception e) {
        logger.error("Error searching events", e);
    }

    return events;
}

From source file:mitm.common.security.ca.hibernate.CertificateRequestDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public CertificateRequestEntity getNextRequest(Date notAfter) {
    DetachedCriteria minDateCriteria = createDetachedCriteria(CertificateRequestEntity.ENTITY_NAME);

    /*//from  ww  w  . j  a  va2  s  .  c  o m
     * Create a criteria to get the oldest nextUpdate
     */
    minDateCriteria.setProjection(Projections.min(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME));

    Criteria criteria = createCriteria(CertificateRequestEntity.ENTITY_NAME);

    criteria.add(Restrictions.or(
            Property.forName(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME).eq(minDateCriteria),
            Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

    /*
     * We only want entries that are older than notAfter or have no nextUpdate yet. The reason for notAfter is
     * that we do not want to try too fast in succession. By setting notAfter to the current date we will only 
     * get entries for which the update is long overdue.
     */
    criteria.add(Restrictions.or(Restrictions.le(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME, notAfter),
            Restrictions.isNull(CertificateRequestEntity.NEXT_UPDATE_COLUMN_NAME)));

    addSortOnCreationDate(criteria);

    CertificateRequestEntity next = null;

    List<CertificateRequestEntity> found = criteria.list();

    if (found != null && found.size() > 0) {
        next = found.get(0);
    }

    return next;
}

From source file:mitm.common.sms.hibernate.SMSGatewayDAO.java

License:Open Source License

public int getAvailableCount(Date notAfter) {
    Criteria criteria = createCriteria(entityName);

    if (notAfter != null) {
        /*/*w  w  w.j  a v a  2  s  .c  om*/
         * We only want entries that are older than notAfter or have no dateLastTry yet
         */
        criteria.add(
                Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
                        Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));
    }

    criteria.setProjection(Projections.rowCount());

    return (Integer) criteria.uniqueResult();
}

From source file:mitm.common.sms.hibernate.SMSGatewayDAO.java

License:Open Source License

/**
 * Returns the entry that has the oldest try date and not after notAfter. If there is no such entry null
 * is returned./*  w w w .  j a va2  s .c om*/
 */
@SuppressWarnings("unchecked")
public SMSGatewayEntity getNextAvailable(Date notAfter) {
    DetachedCriteria minDateCriteria = createDetachedCriteria(entityName);

    /*
     * Create a criteria to get the oldest dateLastTry
     */
    minDateCriteria.setProjection(Projections.min(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()));

    Criteria criteria = createCriteria(entityName);

    criteria.add(Restrictions.or(
            Property.forName(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn()).eq(minDateCriteria),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    /*
     * We only want entries that are older than notAfter or have no dateLastTry yet. The reason for notAfter is
     * that we do not want to try too fast in succession. By setting notAfter in the past we can make sure that
     * we only get entries that are not recently been updated.
     */
    criteria.add(Restrictions.or(Restrictions.le(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn(), notAfter),
            Restrictions.isNull(SMSGatewayEntity.Columns.DATE_LAST_TRY.getColumn())));

    SMSGatewayEntity next = null;

    List<SMSGatewayEntity> found = criteria.list();

    if (found != null && found.size() > 0) {
        next = found.get(0);
    }

    return next;
}