Example usage for org.hibernate.criterion Restrictions ilike

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

Introduction

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

Prototype

public static Criterion ilike(String propertyName, String value, MatchMode matchMode) 

Source Link

Document

A case-insensitive "like" (similar to Postgres ilike operator) using the provided match mode

Usage

From source file:com.klistret.cmdb.utility.hibernate.XPathCriteria.java

License:Open Source License

/**
 * //from www  .  j  a  va  2  s  .c  o m
 * @param predicate
 * @return
 */
protected Criterion getRestriction(Expr predicate, HibernateStep context) {
    logger.debug("Adding restrictions by predicate to context [{}]", context);

    switch (predicate.getType()) {
    case Or:
        /**
         * Recursively breaks down the OrExpr by translating on the first
         * and second operands
         */
        if (((OrExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("OrExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.or(getRestriction(((OrExpr) predicate).getOperands().get(0), context),
                getRestriction(((OrExpr) predicate).getOperands().get(1), context));
    case And:
        /**
         * Recursively breaks down the AndExpr by translating on the first
         * and second operands
         */
        if (((AndExpr) predicate).getOperands().size() != 2)
            throw new ApplicationException(
                    String.format("AndExpr expression [%s] expects 2 operands", predicate));

        return Restrictions.and(getRestriction(((AndExpr) predicate).getOperands().get(0), context),
                getRestriction(((AndExpr) predicate).getOperands().get(1), context));
    case Comparison:
        /**
         * Find the literal
         */
        LiteralExpr literal = getLiteralOperand(((ComparisonExpr) predicate).getOperands());

        /**
         * Find the relative path making a Hibernate relative path
         */
        RelativePathExpr rpe = getRelativePathOperand(((ComparisonExpr) predicate).getOperands());
        HibernateRelativePath hRPath = process(rpe, context);
        build(hRPath);

        HibernateStep last = hRPath.getLastHibernateStep();

        /**
         * Property name with alias prefix
         */
        String alias = last.getPrevious() == null ? aliasCache.get(context.getPath())
                : aliasCache.get(last.getPrevious().getPath());
        String propertyName = alias == null ? last.getName() : String.format("%s.%s", alias, last.getName());

        /**
         * Paths with XML properties (always the last step if present)
         * return a XPath restriction.
         */
        if (hRPath.hasXML()) {
            if (!hRPath.isTruncated())
                throw new ApplicationException(String.format(
                        "Predicate relative path ending in an XML property [%s] must be truncated", last));

            /**
             * Last Hibernate step of the Hibernate path marks the property
             * which the restriction acts on.
             */
            StepExpr step = (StepExpr) last.getStep();

            /**
             * A new XPath is created from the last step downwards till the
             * step prior to the ending step.
             */
            String xpath = null;
            for (int depth = step.getDepth(); depth < step.getRelativePath().getDepth() - 1; depth++) {
                Expr expr = step.getRelativePath().getExpr(depth);
                xpath = xpath == null ? expr.getXPath() : String.format("%s/%s", xpath, expr.getXPath());
            }

            Step ending = (Step) step.getRelativePath().getLastExpr();

            /**
             * A new comparison is generated
             */
            List<Expr> operands = new ArrayList<Expr>();
            operands.add(ending);
            operands.add(literal);

            xpath = String.format("%s[%s]", xpath,
                    ComparisonExpr.getXPath(((ComparisonExpr) predicate).getOperator(), operands, false));
            xpath = String.format("%s%s", context.getBaseExpression().getProlog(), xpath);

            PathExpression other = new PathExpression(xpath);
            return new XPathRestriction(propertyName, (Step) other.getRelativePath().getFirstExpr());
        }

        if (((StepExpr) last.getStep()).hasPredicates())
            throw new ApplicationException(String.format(
                    "Comparisons against Hibernate properties may not have an underlying step [] with predicates",
                    last.getStep()));

        logger.debug("Predicate is comparison [{}] against property [{}]",
                ((ComparisonExpr) predicate).getOperator().name(), propertyName);

        switch (((ComparisonExpr) predicate).getOperator()) {
        case ValueEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.gt(propertyName, literal.getValue().getJavaValue());
        case ValueGreaterThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ge(propertyName, literal.getValue().getJavaValue());
        case ValueLessThan:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.lt(propertyName, literal.getValue().getJavaValue());
        case ValueLessThanOrEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.le(propertyName, literal.getValue().getJavaValue());
        case ValueNotEquals:
            logger.debug("Value: {}", literal.getValue().getJavaValue());
            return Restrictions.ne(propertyName, literal.getValue().getJavaValue());
        case GeneralEquals:
            /**
             * If atomic (not a sequence) then the 'in' restriction is not
             * usable (defaults to 'eq' restriction) since the argument is
             * an array of objects.
             */
            if (literal.isAtomic()) {
                logger.debug("Value: {}", literal.getValue().getJavaValue());
                return Restrictions.eq(propertyName, literal.getValue().getJavaValue());
            }

            logger.debug("Values: {}", literal.getValues());

            Object[] javaValues = new Object[literal.getValues().length];
            for (int index = 0; index < literal.getValues().length; index++)
                javaValues[index] = ((com.klistret.cmdb.utility.saxon.Value) literal.getValues()[index])
                        .getJavaValue();

            return Restrictions.in(propertyName, javaValues);
        case Matches:
            if (((ComparisonExpr) predicate).getOperands().size() != 2)
                throw new ApplicationException(
                        String.format("Matches function [%s] expects 2 operands", predicate));

            logger.debug("Value: {}", literal.getValue().getText());
            return Restrictions.ilike(propertyName, literal.getValue().getText(), MatchMode.EXACT);
        case Exists:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Exists function [%s] expects only 1 operand", predicate));

            return Restrictions.isNotNull(propertyName);
        case Empty:
            if (((ComparisonExpr) predicate).getOperands().size() != 1)
                throw new ApplicationException(
                        String.format("Empty function [%s] expects only 1 operand", predicate));

            return Restrictions.isNull(propertyName);
        default:
            throw new ApplicationException(
                    String.format("Unexpected comparison operator [%s] handling predicates",
                            ((ComparisonExpr) predicate).getOperator()));
        }

    default:
        throw new ApplicationException(String.format("Unexpected expr [%s] type for predicate", predicate));
    }
}

From source file:com.koylubaevnt.library.db.DataHelper.java

public void getBooksByLetter(Character letter) {

    Criterion criterion = Restrictions.ilike("b.name", letter.toString(), MatchMode.START);

    prepareCriterias(criterion);/*from w  w  w  . j  av  a  2 s  .  c o  m*/
    populateList();
}

From source file:com.koylubaevnt.library.db.DataHelper.java

public void getBooksByAuthor(String authorName) {

    Criterion criterion = Restrictions.ilike("author.fio", authorName, MatchMode.ANYWHERE);

    prepareCriterias(criterion);/*w  w w.  j  a v  a  2s  .c  o  m*/
    populateList();
}

From source file:com.koylubaevnt.library.db.DataHelper.java

public void getBooksByName(String bookName) {

    Criterion criterion = Restrictions.ilike("b.name", bookName, MatchMode.ANYWHERE);

    prepareCriterias(criterion);//from   www.j  a v  a 2  s . com
    populateList();
}

From source file:com.library.Database.DataHelper.java

public List<Book> getBookByAuthor(String authorName, int firstNote, int notesNumber) {
    getSession().beginTransaction();/*from  w  w w  . j  av a  2 s.  c  o m*/
    totalBooksNumber = getSession().createCriteria(Book.class).setProjection(Projections.property("id"))
            .createCriteria("author").add(Restrictions.ilike("fio", authorName, MatchMode.ANYWHERE)).list()
            .size();
    List<Book> books = getCriteriaWithProjection().createCriteria("author")
            .add(Restrictions.ilike("fio", authorName, MatchMode.ANYWHERE)).setFirstResult(firstNote)
            .setMaxResults(notesNumber).setResultTransformer(Transformers.aliasToBean(Book.class)).list();
    getSession().getTransaction().commit();
    return books;
}

From source file:com.library.Database.DataHelper.java

private List<Book> getBookList(String field, String value, MatchMode matchMode, int firstNote,
        int notesNumber) {
    getSession().beginTransaction();//from w w w.  ja v a 2 s  . c  o  m
    totalBooksNumber = getSession().createCriteria(Book.class).setProjection(Projections.property("id"))
            .add(Restrictions.ilike(field, value, matchMode)).list().size();
    List<Book> books = getCriteriaWithProjection().add(Restrictions.ilike(field, value, matchMode))
            .setFirstResult(firstNote).setMaxResults(notesNumber)
            .setResultTransformer(Transformers.aliasToBean(Book.class)).list();
    getSession().getTransaction().commit();
    return books;

}

From source file:com.liveneo.plat.web.action.JobmsgAction.java

private DetachedCriteria getDetachedCriteria() {
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(BdJobmsg.class);
    if (StringUtils.isNotEmpty(queryjobname)) {
        detachedCriteria.add(Restrictions.ilike(BdJobmsg.PROP_JOB_NAME, queryjobname, MatchMode.ANYWHERE));
    }//from  w  w  w .jav a 2s . co m
    if (StringUtils.isNotEmpty(queryjobstate)) {
        detachedCriteria.add(Restrictions.eq(BdJobmsg.PROP_JOB_STATE, queryjobstate));
    }
    return detachedCriteria;
}

From source file:com.lm.lic.manager.hibernate.LicenseDAO.java

License:Open Source License

public Integer findNumBoughtLics(String isvId, String prodId) {
    Integer numLics = 0;/*from   w w w  . j  av  a  2s.  com*/
    try {
        Long lpid = Long.parseLong(prodId);
        Long lisvid = Long.parseLong(isvId);
        Criteria criteria = getSession().createCriteria(License.class);
        criteria.add(Restrictions.eq("isv.id", lisvid));
        criteria.add(Restrictions.eq("product.id", lpid));
        MatchMode matchMode = MatchMode.START;
        criteria.add(Restrictions.ilike("paymentStatus", LicensePaymentStatus.PAID.name(), matchMode));
        criteria.setProjection(Projections.rowCount());
        numLics = (Integer) criteria.list().get(0);
    } catch (RuntimeException re) {
        log.error("find by property name failed", re);
        throw re;
    }
    return numLics;
}

From source file:com.lm.lic.manager.hibernate.LicenseDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<License> findUsedLicenses(String isvId, Boolean decomStatus, String licKey, String deviceId,
        String customerEmail, int licLifeInDays) {
    List<License> licenses = null;
    try {// w  w w .  ja  v a 2s.  co  m
        Long lisvId = Long.parseLong(isvId);
        boolean decom = decomStatus == null ? false : decomStatus.booleanValue();

        Criteria criteria = getSession().createCriteria(License.class);

        criteria.add(Restrictions.eq("isv.id", lisvId));
        criteria.add(Restrictions.eq("inUse", true));
        criteria.add(Restrictions.eq("decom", decom));

        if (StringUtils.hasText(licKey)) {
            Criterion licKeyCrit = Restrictions.ilike("licKey", licKey, MatchMode.ANYWHERE);
            criteria.add(licKeyCrit);
        }

        if (StringUtils.hasText(deviceId)) {
            Criterion devIdCrit = Restrictions.ilike("endUserPin", deviceId, MatchMode.ANYWHERE);
            criteria.add(devIdCrit);
        }

        if (StringUtils.hasText(customerEmail)) {
            Criterion emailCrit = Restrictions.ilike("endUserEmail", customerEmail, MatchMode.ANYWHERE);
            criteria.add(emailCrit);
        }

        if (licLifeInDays > 0) {
            Criterion lifeCrit = Restrictions.eq("lifeInDays", licLifeInDays);
            criteria.add(lifeCrit);
        }

        licenses = criteria.list();
    } catch (RuntimeException re) {
        log.error("find by property name failed", re);
        throw re;
    }
    return licenses;
}

From source file:com.mac.green_leaves.v1.master.MasterRepository.java

public List<Model> list(String keyword, Integer pageNumber, Integer branch, Class modelClass) {
    Session session = getSession();/*from ww  w.  j a v  a  2  s . c o  m*/

    Criteria criteria = session.createCriteria(modelClass);

    if (keyword != null) {
        Field[] fields = modelClass.getDeclaredFields();
        ArrayList<Criterion> criterions = new ArrayList<>();
        for (Field field : fields) {
            if (field.getType().isAssignableFrom(String.class)) {
                criterions.add(Restrictions.ilike(field.getName(), keyword, MatchMode.ANYWHERE));
            }
        }
        criteria.add(Restrictions.or(criterions.toArray(new Criterion[] {})));
    }

    criteria.add(Restrictions.eq("branch", branch));

    if (pageNumber != null) {
        criteria.setFirstResult(PAGE_SIZE * (pageNumber - 1));
        criteria.setMaxResults(PAGE_SIZE);
    }

    return criteria.list();
}