Example usage for org.hibernate.criterion CriteriaQuery getColumnsUsingProjection

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

Introduction

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

Prototype

public String[] getColumnsUsingProjection(Criteria criteria, String propertyPath) throws HibernateException;

Source Link

Document

Get the names of the columns mapped by a property path.

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 ww.  j  av a 2 s  . c om
        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.closertag.smartmove.server.content.persistence.hibernate.ContainsRestriction.java

License:Open Source License

public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    String[] columnName = criteriaQuery.getColumnsUsingProjection(criteria,
            alias + "." + GidZone.POLYGON_COLUMN_NAME);
    // String columnName = criteriaQuery.getColumn(criteria,
    // );/*from   w  ww .jav  a 2  s.  c  o m*/
    StringBuffer result = new StringBuffer(" st_within(")
            .append(" PointFromText('POINT(" + geometry.getX() + " " + geometry.getY() + ")',4326)  ,")
            .append(columnName[0] + ")");
    return result.toString();

}

From source file:com.closertag.smartmove.server.content.persistence.hibernate.DistanceRestriction.java

License:Open Source License

public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    String[] columnName = criteriaQuery.getColumnsUsingProjection(criteria,
            alias + "." + GpsPosition.LOCATION_COLUMN_NAME);

    StringBuffer result = new StringBuffer("( distance_sphere(").append(columnName[0]).append(", ?) <=")
            .append(this.distance).append(")");
    return useIndex ? result.append(" AND ")
            .append(getBoundingBox(//from   w  w w.j  a v a  2 s .  co  m
                    criteriaQuery.getSQLAlias(criteria, alias + "." + GpsPosition.LOCATION_COLUMN_NAME),
                    this.point.getY(), this.point.getX(), distance))
            .toString() : result.toString();

}

From source file:com.gisgraphy.hibernate.criterion.ProjectionOrder.java

License:Open Source License

@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    Order nso = new NativeSQLOrder(criteriaQuery.getColumnsUsingProjection(criteria, aliasName)[0],
            this.ascending);
    return nso.toSqlString(criteria, criteriaQuery);

}

From source file:com.gisgraphy.hibernate.criterion.ProjectionOrderTest.java

License:Open Source License

@Test
public void testProjectionOrderShouldTakeAscOrderIntoAccount() {
    CriteriaQuery criteriaQuery = EasyMock.createMock(CriteriaQuery.class);
    String[] projectionAlias = { "colProjalias" };
    EasyMock.expect(//w ww .  j  av  a  2s. c om
            criteriaQuery.getColumnsUsingProjection((Criteria) EasyMock.anyObject(), EasyMock.eq(alias)))
            .andReturn(projectionAlias).once();
    EasyMock.expect(criteriaQuery.getSQLAlias((Criteria) EasyMock.anyObject())).andReturn("this_alias").once();
    EasyMock.replay(criteriaQuery);
    ProjectionOrder dorder = new ProjectionOrder(alias, true);
    String sqlString = dorder.toSqlString(null, criteriaQuery);
    assertTrue(sqlString.contains("asc"));
    EasyMock.verify(criteriaQuery);
}

From source file:com.gisgraphy.hibernate.criterion.ProjectionOrderTest.java

License:Open Source License

@Test
public void testProjectionOrderShouldHaveAscOrderByDefault() {
    CriteriaQuery criteriaQuery = EasyMock.createMock(CriteriaQuery.class);
    String[] projectionAlias = { "colProjalias" };
    EasyMock.expect(/*from  ww  w  . j a v  a 2s . com*/
            criteriaQuery.getColumnsUsingProjection((Criteria) EasyMock.anyObject(), EasyMock.eq(alias)))
            .andReturn(projectionAlias).once();
    EasyMock.expect(criteriaQuery.getSQLAlias((Criteria) EasyMock.anyObject())).andReturn("this_alias").once();
    EasyMock.replay(criteriaQuery);
    ProjectionOrder dorder = new ProjectionOrder(alias);
    String sqlString = dorder.toSqlString(null, criteriaQuery);
    assertTrue(sqlString.contains("asc"));
    EasyMock.verify(criteriaQuery);
}

From source file:com.gisgraphy.hibernate.criterion.ProjectionOrderTest.java

License:Open Source License

@Test
public void testProjectionOrderShouldTakeDescOrderIntoAccount() {
    CriteriaQuery criteriaQuery = EasyMock.createMock(CriteriaQuery.class);
    String[] projectionAlias = { "colProjalias" };
    EasyMock.expect(/*from  w ww. j a  v a 2  s  .c om*/
            criteriaQuery.getColumnsUsingProjection((Criteria) EasyMock.anyObject(), EasyMock.eq(alias)))
            .andReturn(projectionAlias).once();
    EasyMock.expect(criteriaQuery.getSQLAlias((Criteria) EasyMock.anyObject())).andReturn("this_alias").once();
    EasyMock.replay(criteriaQuery);
    ProjectionOrder dorder = new ProjectionOrder(alias, false);
    String sqlString = dorder.toSqlString(null, criteriaQuery);
    assertTrue(sqlString.contains("desc"));
    EasyMock.verify(criteriaQuery);
}

From source file:com.heliosapm.aa4h.criterion.LiteralInExpression.java

License:Apache License

/**
 * Render the SQL fragment// ww w .  j av  a2  s.  c o m
 * @param criteria
 * @param criteriaQuery
 * @return the rendered SQL fragment
 * @throws HibernateException
 * @see org.hibernate.criterion.Criterion#toSqlString(org.hibernate.Criteria, org.hibernate.criterion.CriteriaQuery)
 */
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    StringBuffer sqlFragment = new StringBuffer();
    String[] propertyColumnNames = criteriaQuery.getColumnsUsingProjection(criteria, propertyName);
    renderColumnNames(propertyColumnNames, sqlFragment);

    sqlFragment.append(" in (").append(valueList).append(')');

    return sqlFragment.toString();
}

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");
    }//from   www .  j  a  v a2  s . co  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 {
    /**/*from   ww  w.  j  ava  2  s  .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);
}