Example usage for org.hibernate.criterion CriteriaQuery getFactory

List of usage examples for org.hibernate.criterion CriteriaQuery getFactory

Introduction

In this page you can find the example usage for org.hibernate.criterion CriteriaQuery getFactory.

Prototype

public SessionFactoryImplementor getFactory();

Source Link

Document

Provides access to the SessionFactory

Usage

From source file:com.belle.yitiansystem.merchant.service.impl.MerchantsService.java

@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
    Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
    StringBuffer fragment = new StringBuffer();
    for (int i = 0; i < columns.length; i++) {
        SessionFactoryImplementor factory = criteriaQuery.getFactory();
        boolean lower = ignoreCase && type.sqlTypes(factory)[i] == Types.VARCHAR;
        if (lower) {
            fragment.append(factory.getDialect().getLowercaseFunction()).append('(');
        }// w w  w . j ava 2  s  .com
        fragment.append("CONVERT( " + columns[i] + " USING " + encoding + " )");
        if (lower)
            fragment.append(')');
        fragment.append(ascending ? " asc" : " desc");
        if (i < columns.length - 1)
            fragment.append(", ");
    }
    return fragment.toString();
}

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

License:Open Source License

public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery)
        throws HibernateException {
    final String functionFragment = getFunction(criteriaQuery).render(StringType.INSTANCE,
            buildFunctionParameterList(criteria, criteriaQuery), criteriaQuery.getFactory());
    return functionFragment + " as y" + position + '_';
}

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

License:Open Source License

/**
 * Copied from AggregateProjection/*w w w .ja  v a2  s  .com*/
 */
public Type[] getTypes(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    return new Type[] {
            getFunction(criteriaQuery).getReturnType(StringType.INSTANCE, criteriaQuery.getFactory()) };
}

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

License:Open Source License

/**
 * Copied from AggregateProjection/*  w  w w  .ja va 2s .  c  o m*/
 */
protected SQLFunction getFunction(String functionName, CriteriaQuery criteriaQuery) {
    SQLFunction function = criteriaQuery.getFactory().getSqlFunctionRegistry().findSQLFunction(functionName);
    if (function == null) {
        throw new HibernateException("Unable to locate mapping for function named [" + functionName + "]");
    }
    return function;
}

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

License:Open Source License

private List<String> buildFunctionParameterList(Criteria criteria, CriteriaQuery criteriaQuery) {
    Dialect dialect = criteriaQuery.getFactory().getDialect();
    String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);

    if (columns.length != 1) {
        logger.error("XMLQUERY may only be used with single-column properties [property: {}]", propertyName);
        throw new HibernateException("XMLQUERY may only be used with single-column properties");
    }// w  w w .j a v  a  2  s . c o m

    BaseExpression be = step.getRelativePath().getBaseExpression();

    /**
     * Property type is generalized to wild-card "*" leaving only the
     * predicate
     */
    String axis = String.format("%s:%s", step.getQName().getPrefix(), step.getQName().getLocalPart());

    /**
     * Passing clause
     */
    String passingClause = String.format("PASSING %s AS \"%s\"", columns[0], variableReference);

    /**
     * Setup XPath first with the variable reference (acts a root), the axis
     * is replaced and then XPath is built up again either from generated
     * string or the raw XPath for each step (depending on if it is a
     * readable step or irresolute).
     */
    String xpath = String.format("$%s", variableReference);

    for (Expr expr : step.getRelativePath().getSteps()) {
        if (expr instanceof Step) {
            if (((Step) expr).getDepth() >= step.getDepth()) {
                if (expr instanceof StepExpr) {
                    xpath = String.format("%s/%s", xpath, expr.getXPath(true));
                }
                if (expr instanceof IrresoluteExpr) {
                    xpath = String.format("%s/%s", xpath,
                            step.getRelativePath().getRawXPath(((Step) expr).getDepth()));
                }
            }
        }
    }

    xpath = xpath.replaceFirst(axis, "*");
    logger.debug("XPath [{}] prior prefixing default function declaration and namespace declarations", xpath);

    /**
     * Concatenate namespace declarations
     */
    for (String namespace : be.getNamespaces())
        xpath = namespace.concat(xpath);

    /**
     * Concatenate default element namespace declaration
     */
    if (be.getDefaultElementNamespace() != null)
        xpath = be.getDefaultElementNamespace().concat(xpath);

    /**
     * Dialect controlls
     */
    if (dialect instanceof DB2Dialect) {
        /**
         * DB2 only allows SQL with double quotes (or at least that is the
         * extend of my knowledge)
         */
        Matcher sq = singleQuotes.matcher(xpath);
        if (sq.find())
            throw new ApplicationException(String
                    .format("XPath [%s] contains surrounding single quotes which DB2 does not allow", xpath),
                    new UnsupportedOperationException());
    }

    /**
     * Return the XMLQuery predicate
     */
    String[] results = {
            String.format("XMLCAST(XMLQUERY(\'%s\' %s) AS VARCHAR(%d))", xpath, passingClause, varcharLimit) };
    return Arrays.asList(results);
}

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

License:Open Source License

@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    /**/* w w  w . java2s  .  c  o m*/
     * Establish dialect, property information about this column
     */
    Dialect dialect = criteriaQuery.getFactory().getDialect();
    String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);

    if (columns.length != 1) {
        logger.error("XMLEXISTS may only be used with single-column properties [property: {}]", propertyName);
        throw new HibernateException("XMLEXISTS may only be used with single-column properties");
    }

    /**
     * Path Expression
     */
    BaseExpression be = step.getRelativePath().getBaseExpression();

    /**
     * Property type is generalized to wild-card "*" leaving only the
     * predicate
     */
    String axis = String.format("%s:%s", step.getQName().getPrefix(), step.getQName().getLocalPart());

    /**
     * Passing clause
     */
    String passingClause = String.format("PASSING %s AS \"%s\"", columns[0], variableReference);

    /**
     * Setup XPath first with the variable reference (acts a root), the axis
     * is replaced and then XPath is built up again either from generated
     * string or the raw XPath for each step (depending on if it is a
     * readable step or irresolute).
     */
    String xpath = String.format("$%s", variableReference);

    String sqlMask = baseMask;
    for (Expr expr : step.getRelativePath().getSteps()) {
        if (expr instanceof Step) {
            if (((Step) expr).getDepth() >= step.getDepth()) {
                if (expr instanceof StepExpr) {
                    xpath = String.format("%s/%s", xpath, expr.getXPath(true));

                    for (Value value : ((StepExpr) expr).getValues()) {
                        if (value.getText().length() > varcharLimit)
                            throw new ApplicationException(
                                    String.format("Literal value [%s] is larger than VARCHAR limiation [%d]",
                                            value.getText(), varcharLimit));

                        String xpathMask = value.getMask();
                        passingClause = String.format("%s, CAST (? AS VARCHAR(%d)) AS \"%s\"", passingClause,
                                varcharLimit, xpathMask);

                        typedValues.add(new TypedValue(stringType, value.getText(), EntityMode.POJO));
                        logger.debug("Adding StringType [value: {}] to restriction with variable [{}]",
                                value.getText(), xpathMask);

                        /**
                         * Use a common mask to reduce the variation in
                         * generated SQL
                         */
                        xpath = xpath.replaceAll(xpathMask, sqlMask);
                        passingClause = passingClause.replaceAll(xpathMask, sqlMask);
                        logger.debug("Replaced XPath mask {} with a common SQL mask {}", xpathMask, sqlMask);

                        sqlMask = incrementMask(sqlMask);
                    }
                }
                if (expr instanceof IrresoluteExpr) {
                    xpath = String.format("%s/%s", xpath,
                            step.getRelativePath().getRawXPath(((Step) expr).getDepth()));
                }
            }
        }
    }

    xpath = xpath.replaceFirst(axis, "*");
    logger.debug("XPath [{}] prior prefixing default function declaration and namespace declarations", xpath);

    /**
     * Concatenate namespace declarations
     */
    for (String namespace : be.getNamespaces())
        xpath = namespace.concat(xpath);

    /**
     * Concatenate default element namespace declaration
     */
    if (be.getDefaultElementNamespace() != null)
        xpath = be.getDefaultElementNamespace().concat(xpath);

    if (dialect instanceof DB2Dialect) {
        /**
         * DB2 only allows SQL with double quotes (or at least that is the
         * extend of my knowledge)
         */
        Matcher sq = singleQuotes.matcher(xpath);
        if (sq.find())
            throw new ApplicationException(String
                    .format("XPath [%s] contains surrounding single quotes which DB2 does not allow", xpath),
                    new UnsupportedOperationException());
    }

    /**
     * Return the XMLEXISTS predicate
     */
    return String.format("XMLEXISTS(\'%s\' %s)", xpath, passingClause);
}

From source file:corner.orm.hibernate.expression.NewExpressionExample.java

License:Apache License

public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {

    EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(criteriaQuery.getEntityName(criteria));
    String[] propertyNames = meta.getPropertyNames();
    Type[] propertyTypes = meta.getPropertyTypes();
    //TODO: get all properties, not just the fetched ones!
    Object[] values = meta.getPropertyValues(entity, getEntityMode(criteria, criteriaQuery));
    List<TypedValue> list = new ArrayList<TypedValue>();
    for (int i = 0; i < propertyNames.length; i++) {
        Object value = values[i];
        Type type = propertyTypes[i];
        String name = propertyNames[i];

        boolean isPropertyIncluded = i != meta.getVersionProperty() && isPropertyIncluded(value, name, type);

        if (isPropertyIncluded) {
            if (propertyTypes[i].isComponentType()) {
                addComponentTypedValues(name, value, (AbstractComponentType) type, list, criteria,
                        criteriaQuery);//  w w w.  j a va 2  s .  co  m
            } else {
                addPropertyTypedValue(name, value, type, list);
            }
        }
    }
    return (TypedValue[]) list.toArray(TYPED_VALUES);
}

From source file:corner.orm.hibernate.expression.NewExpressionExample.java

License:Apache License

private EntityMode getEntityMode(Criteria criteria, CriteriaQuery criteriaQuery) {
    EntityPersister meta = criteriaQuery.getFactory().getEntityPersister(criteriaQuery.getEntityName(criteria));
    EntityMode result = meta.guessEntityMode(entity);
    if (result == null) {
        throw new ClassCastException(entity.getClass().getName());
    }/*from  www  . j  a  v  a2 s.  co m*/
    return result;
}

From source file:corner.orm.hibernate.expression.StringExpression.java

License:Apache License

/**
 * @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria,
 *      org.hibernate.criterion.CriteriaQuery)
 *///from  w  w  w .  jav a  2  s.c  o m
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
    Type type = criteriaQuery.getTypeUsingProjection(criteria, propertyName);
    StringBuffer fragment = new StringBuffer();
    if (columns.length > 1)
        fragment.append('(');
    SessionFactoryImplementor factory = criteriaQuery.getFactory();
    int[] sqlTypes = type.sqlTypes(factory);
    for (int i = 0; i < columns.length; i++) {
        boolean lower = ignoreCase && (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR);
        //??1
        if (exps.size() > 1) {
            fragment.append('(');
        }
        for (ExpPair p : exps) {
            fragment.append(" " + p.exp + " ");
            if (lower) {
                fragment.append(factory.getDialect().getLowercaseFunction()).append('(');
            }
            fragment.append(columns[i]);
            if (lower)
                fragment.append(')');
            fragment.append(getOp()).append("?");

        }
        if (exps.size() > 1) {
            fragment.append(')');
        }

        if (i < columns.length - 1)
            fragment.append(" and ");
    }
    if (columns.length > 1)
        fragment.append(')');
    return fragment.toString();

}

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

License:Apache License

@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    final SessionFactoryImplementor factory = criteriaQuery.getFactory();
    final Dialect dialect = factory.getDialect();
    final String[] columns = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);

    if (columns.length != 1)
        throw new HibernateException("ilike may only be used with single-column properties");

    final String columnName = columns[0];
    final String s = matchMode.toMatchString(factory, columnName);

    if (dialect instanceof PostgreSQLDialect) {
        return "? ilike " + s;
    } else {//from   w  w  w.  j a  v a 2s . c om
        return "? like " + dialect.getLowercaseFunction() + "(" + s + ")";
    }

}