Example usage for org.hibernate.criterion Restrictions sqlRestriction

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

Introduction

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

Prototype

public static Criterion sqlRestriction(String sql) 

Source Link

Document

Apply a constraint expressed in SQL with no JDBC parameters.

Usage

From source file:de.tudarmstadt.ukp.lmf.api.Uby.java

License:Apache License

/**
 * This method finds all {@link PredicateArgumentAxis} instances whose id contains the specified
 * {@link String} in the database accessed by this {@link Uby} instance.
 *
 * @param senseAxisId/*  w  w w.  ja va2s  .co  m*/
 *            string contained in the identifiers of the predicate-argument axes to be returned
 *
 * @return the {@link List} of all predicate-argument axes whose id contains the specified string.<br>
 *         This method returns an empty list if no axis contains the specified string in
 *         its id or the specified string is null.
 *
 * @see #getPredicateArgumentAxes()
 * @see #getSenseAxesBySense(Sense)
 */
public List<PredicateArgumentAxis> getPredicateArgumentAxesByIdPattern(String axisId) {
    Criteria criteria = session.createCriteria(PredicateArgumentAxis.class);
    criteria = criteria.add(Restrictions.sqlRestriction("predicateArgumentAxisId like '%" + axisId + "%'"));

    @SuppressWarnings("unchecked")
    List<PredicateArgumentAxis> result = criteria.list();
    if (result == null) {
        result = new ArrayList<PredicateArgumentAxis>(0);
    }
    return result;
}

From source file:de.tudarmstadt.ukp.lmf.api.UbyStatistics.java

License:Apache License

/**
 * Return a {@link Set} of {@link String} instances consisting of <code>lemma+"_"+part-of-speech</code>,
 *       filtered by given {@link Lexicon} name, part-of-speech prefix and a language identifier.<br>
 * The lemma is obtained from the written form of the first {@link FormRepresentation} of the {@link Lemma}
 * instance./*from   w w w. ja va2s  . c  o m*/
 * 
 * @param lexiconName
 *          name of the lexicon which lemmas should be used
 * 
 * @param prefix the part-of-speech prefix used when filtering {@link LexicalEntry} instances
 * 
 * @param lang the language identifier used when filtering lexical entries
 * 
 * @return a set of strings containing lemma and part-of-speech of the specified lexicon.<br>
 * 
 * This method returns an empty set if the lexicon with the specified name does no exist or
 * the lexicon does not contain any lexical entries with specified part-of-speech prefix and language
 * identifier.
 * 
 * @see Lemma#getFormRepresentations()
 * @see FormRepresentation#getWrittenForm()
 * @see EPartOfSpeech
 * @see ELanguageIdentifier
 */
public Set<String> getLemmaPosPerLexiconAndPosPrefixAndLanguage(String lexiconName, String prefix,
        String lang) {
    Criteria criteria = session.createCriteria(Lexicon.class, "l");

    criteria = criteria.createCriteria("lexicalEntries", "e");
    if (lexiconName != null) {
        criteria = criteria.add(Restrictions.eq("l.name", lexiconName));
    }
    if (lang != null) {
        criteria = criteria.add(Restrictions.eq("l.languageIdentifier", lang));
    }
    if (prefix != null) {
        criteria = criteria.add(Restrictions.sqlRestriction("partOfSpeech like '" + prefix + "'"));
    }
    criteria = criteria.createCriteria("lemma").createCriteria("formRepresentations", "f")
            .setProjection(Projections.projectionList().add(Property.forName("f.writtenForm"))
                    .add(Property.forName("e.partOfSpeech")));
    ScrollableResults res = criteria.scroll();
    ArrayList<String> out = new ArrayList<String>();
    while (res.next()) {
        Object[] r = res.get();
        if (r[1] != null) {
            out.add((String) r[0] + "_" + ((EPartOfSpeech) r[1]).toString());
        } else {
            out.add((String) r[0] + "_null");
        }
    }
    HashSet<String> out2 = new HashSet<String>(out);
    return out2;

}

From source file:de.tudarmstadt.ukp.lmf.transform.DBToXMLTransformer.java

License:Apache License

protected void doTransform(boolean includeAxes, final Lexicon... includeLexicons) throws SAXException {
    final int bufferSize = 100;
    commitCounter = 1;/*from w w  w  .ja  va 2 s  . c o  m*/

    writeStartElement(lexicalResource);

    // Iterate over all lexicons
    if (includeLexicons == null || includeLexicons.length > 0) {
        for (Lexicon lexicon : lexicalResource.getLexicons()) {
            String lexiconName = lexicon.getName();

            // Check if we want to include this lexicon.
            if (includeLexicons != null) {
                boolean found = false;
                for (Lexicon l : includeLexicons) {
                    if (lexiconName.equals(l.getName())) {
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    continue;
                }
            }

            logger.info("Processing lexicon: " + lexiconName);
            writeStartElement(lexicon);

            // Iterate over all possible sub-elements of this Lexicon and
            // write them to the XML
            Class<?>[] lexiconClassesToSave = { LexicalEntry.class, SubcategorizationFrame.class,
                    SubcategorizationFrameSet.class, SemanticPredicate.class, Synset.class,
                    SynSemCorrespondence.class,
                    //ConstraintSet.class
            };

            //  "Unfortunately, MySQL does not treat large offset values efficiently by default and will still read all the rows prior to an offset value. It is common to see a query with an offset above 100,000 take over 20 times longer than an offset of zero!"
            // http://www.numerati.com/2012/06/26/reading-large-result-sets-with-hibernate-and-mysql/
            for (Class<?> clazz : lexiconClassesToSave) {
                /*DetachedCriteria criteria = DetachedCriteria.forClass(clazz)
                      .add(Restrictions.sqlRestriction("lexiconId = '" + lexicon.getId() + "'"));
                CriteriaIterator<Object> iter = new CriteriaIterator<Object>(criteria, sessionFactory, bufferSize);
                while (iter.hasNext()) {
                   Object obj = iter.next();
                   writeElement(obj);
                   session.evict(obj);
                   commitCounter++;
                   if (commitCounter % 1000 == 0)
                      logger.info("progress: " + commitCounter  + " class instances written to file");
                }*/
                Session lookupSession = sessionFactory.openSession();
                Query query = lookupSession.createQuery("FROM " + clazz.getSimpleName() + " WHERE lexiconId = '"
                        + lexicon.getId() + "' ORDER BY id");
                query.setReadOnly(true);
                if (DBConfig.MYSQL.equals(dbConfig.getDBType())) {
                    query.setFetchSize(Integer.MIN_VALUE); // MIN_VALUE gives hint to JDBC driver to stream results
                } else {
                    query.setFetchSize(1000);
                }
                ScrollableResults results = query.scroll(ScrollMode.FORWARD_ONLY);
                while (results.next()) {
                    // For streamed query results, no further queries are allowed (incl. lazy proxy queries!)
                    // Detach the object from the lookup session and reload it using the "official" session.
                    Object[] rows = results.get();
                    Object row = rows[0];
                    lookupSession.evict(row);
                    lookupSession.evict(rows);
                    rows = null;
                    row = session.get(row.getClass(), ((IHasID) row).getId());
                    writeElement(row);
                    session.evict(row);
                    row = null;
                    commitCounter++;
                    if (commitCounter % 1000 == 0) {
                        logger.info("progress: " + commitCounter + " class instances written to file");
                    }
                    if (commitCounter % 10000 == 0) {
                        closeSession();
                        openSession();
                    }
                }
                results.close();
                lookupSession.close();
            }
            writeEndElement(lexicon);
        }
    }

    // Iterate over SenseAxes and write them to XMLX when not only
    // lexicons should be converted
    if (includeAxes) {
        logger.info("Processing sense axes");
        DetachedCriteria criteria = DetachedCriteria.forClass(SenseAxis.class)
                .add(Restrictions.sqlRestriction("lexicalResourceId = '" + lexicalResource.getName() + "'"));
        CriteriaIterator<Object> iter = new CriteriaIterator<Object>(criteria, sessionFactory, bufferSize);
        while (iter.hasNext()) {
            Object obj = iter.next();
            writeElement(obj);
            session.evict(obj);
            commitCounter++;
            if (commitCounter % 1000 == 0) {
                logger.info("progress: " + commitCounter + " class instances written to file");
            }
        }

        logger.info("Processing predicateargument axes");
        DetachedCriteria criteria2 = DetachedCriteria.forClass(PredicateArgumentAxis.class)
                .add(Restrictions.sqlRestriction("lexicalResourceId = '" + lexicalResource.getName() + "'"));
        CriteriaIterator<Object> iter2 = new CriteriaIterator<Object>(criteria2, sessionFactory, bufferSize);
        while (iter2.hasNext()) {
            Object obj = iter2.next();
            writeElement(obj);
            session.evict(obj);
            commitCounter++;
            if (commitCounter % 1000 == 0) {
                logger.info("progress: " + commitCounter + " class instances written to file");
            }
        }

    }
    writeEndElement(lexicalResource);

    writeEndDocument();
}

From source file:edu.utah.further.core.data.hibernate.query.CriterionBuilderHibernateImpl.java

License:Apache License

/**
 * @param criterion//from   w w w . ja  va 2s .c  o m
 * @see #visit(net.SQLCriterionImpl.core.search.SQLCriterion)
 */
public void visitSql() {
    final String sql = (String) criterion.getParameter(0);
    result = Restrictions.sqlRestriction(sql);
}

From source file:entidades.Amistad.AmistadDAOHibernate.java

@Override
public List<Amistad> obtenerAmigos(int idUsuario) {
    Criterion res = Restrictions.sqlRestriction("user1='" + idUsuario + "'");
    Criteria criteria = this.sesion.createCriteria(Amistad.class);
    criteria.add(res);//from   w  ww.  j  ava  2  s.  c o m
    return criteria.list();
}

From source file:entidades.Usuario.UsuarioDAOHibernate.java

@Override
public Usuario validarUsuario(String user, String pass) {
    Criterion res = Restrictions.sqlRestriction("user='" + user + "' and pass='" + pass + "'");
    Criteria criteria = this.sesion.createCriteria(Usuario.class);
    criteria.add(res);//  ww w.j av a2s  .c  o  m
    return (Usuario) criteria.uniqueResult();

}

From source file:es.emergya.bbdd.dao.CapaInformacionHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Throwable.class)
public List<CapaInformacion> getAll(boolean base, Boolean historico) {
    List<CapaInformacion> res = new LinkedList<CapaInformacion>();
    try {/*from w  w w  . ja va  2s  .c  o  m*/
        Session currentSession = getSession();
        currentSession.clear();
        Criteria criteria = currentSession.createCriteria(CapaInformacion.class).addOrder(Order.desc("orden"))
                .add(Restrictions.eq("opcional", (!base))).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

        if (!base) {
            if (historico != null) {
                criteria = criteria.createCriteria("capasInformacion");
                if (!historico) {
                    criteria.add(Restrictions.eq("visibleGPS", true));
                } else {
                    criteria.add(Restrictions.eq("visibleHistorico", true));
                }
                criteria = criteria.add(Restrictions
                        .sqlRestriction("{alias}.fk_usuarios = " + Authentication.getUsuario().getId()));
            }
        }

        res = (List<CapaInformacion>) criteria.list();
    } catch (Throwable t) {
        log.error(t, t);
    }
    return res;
}

From source file:es.emergya.bbdd.dao.RecursoHome.java

License:Open Source License

@SuppressWarnings("unchecked")
@Transactional(readOnly = true, rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
public List<Recurso> getByFilter(Recurso p) {
    List<Recurso> res = new ArrayList<Recurso>(0);
    try {//from   w  w  w  .ja v  a 2s  .com
        Session currentSession = getSession();
        currentSession.clear();
        Criteria criteria = currentSession.createCriteria(Recurso.class);

        if (p.getInfoAdicional() != null) {
            criteria = criteria.add(
                    Restrictions.ilike("infoAdicional", LogicConstants.getGenericString(p.getInfoAdicional())));
        }
        if (p.getNombre() != null) {
            criteria = criteria
                    .add(Restrictions.ilike("nombre", LogicConstants.getGenericString(p.getNombre())));
        }

        if (p.getIdentificador() != null) {
            criteria = criteria.add(
                    Restrictions.ilike("identificador", LogicConstants.getGenericString(p.getIdentificador())));
        }

        if (p.getHabilitado() != null) {
            criteria = criteria.add(Restrictions.eq("habilitado", p.getHabilitado()));
        }
        if (p.idpattern != null && p.idpattern.length() > 0) {
            criteria.add(Restrictions.sqlRestriction("lpad({alias}.dispositivo :: varchar, " + LONGITUD_ISSI
                    + ", '0') ilike '" + LogicConstants.getGenericString(p.idpattern) + "'"));
        }

        if (p.getEstadoEurocop() != null) {
            criteria = criteria.add(Restrictions.ilike("estadoEurocop",
                    LogicConstants.getGenericString(p.getEstadoEurocop().getIdentificador())));
        }

        if (p.getFlotas() != null) {
            criteria = criteria.add(Restrictions.eq("flotas", p.getFlotas()));
        }

        if (p.getPatrullas() != null) {
            criteria = criteria.add(Restrictions.eq("patrullas", p.getPatrullas()));
        }

        if (p.getTipo() != null) {
            criteria = criteria
                    .add(Restrictions.ilike("tipo", LogicConstants.getGenericString(p.getTipoReal())));
        }

        log.trace(criteria);

        res = criteria.addOrder(Order.asc("nombre")).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();

        for (Recurso uniqueResult : res) {
            if (uniqueResult != null) {
                if (uniqueResult.getPatrullas() != null) {
                    uniqueResult.getPatrullas().getId();
                }
                if (uniqueResult.getFlotas() != null) {
                    uniqueResult.getFlotas().getId();
                }
            }
        }
    } catch (Throwable t) {
        log.error(t, t);
    }
    return res;
}

From source file:eu.interedition.text.query.AnyCriterion.java

License:Apache License

@Override
Criterion restrict() {
    return Restrictions.sqlRestriction("1 = 1");
}

From source file:eu.interedition.text.query.NoneCriterion.java

License:Apache License

@Override
Criterion restrict() {
    return Restrictions.sqlRestriction("1 <> 1");
}