Search in sources :

Example 1 with OgnlHqlFormat

use of com.manydesigns.elements.text.OgnlHqlFormat in project Portofino by ManyDesigns.

the class QueryUtils method runSql.

/**
 * Runs a SQL query against a session. The query is processed with an {@link OgnlSqlFormat}, so it can
 * access values from the OGNL context.
 * @param session the session
 * @param sql the query string
 * @return the results of the query as an Object[] (an array cell per column)
 */
public static List<Object[]> runSql(Session session, String sql) {
    OgnlHqlFormat hqlFormat = OgnlHqlFormat.create(sql);
    String formatString = hqlFormat.getFormatString();
    Object[] parameters = hqlFormat.evaluateOgnlExpressions(null);
    return runSql(session, formatString, parameters);
}
Also used : OgnlHqlFormat(com.manydesigns.elements.text.OgnlHqlFormat)

Example 2 with OgnlHqlFormat

use of com.manydesigns.elements.text.OgnlHqlFormat in project Portofino by ManyDesigns.

the class QueryUtils method getObjectByPk.

/**
 * Loads an object by primary key. It also verifies that the object falls within the results of a given query.
 * @param persistence the persistence object
 * @param database the database (connection provider)
 * @param entityName the name of the entity to load
 * @param pk the primary key object
 * @param hqlQueryString the query (where condition) that the object must fulfill
 * @param rootObject the OGNL rootFactory object against which to evaluate the query string.
 * @return the loaded object, or null if an object with that key does not exist or falls outside the query.
 */
public static Object getObjectByPk(Persistence persistence, String database, String entityName, Serializable pk, String hqlQueryString, Object rootObject) {
    TableAccessor table = persistence.getTableAccessor(database, entityName);
    List<Object> result;
    PropertyAccessor[] keyProperties = table.getKeyProperties();
    OgnlHqlFormat hqlFormat = OgnlHqlFormat.create(hqlQueryString);
    String formatString = hqlFormat.getFormatString();
    Object[] ognlParameters = hqlFormat.evaluateOgnlExpressions(rootObject);
    int p = ognlParameters.length;
    Object[] parameters = new Object[p + keyProperties.length];
    System.arraycopy(ognlParameters, 0, parameters, 0, p);
    try {
        PlainSelect parsedQuery = parseQuery(new CCJSqlParserManager(), formatString);
        if (parsedQuery.getWhere() == null) {
            return getObjectByPk(persistence, database, entityName, pk);
        }
        Alias mainEntityAlias = getEntityAlias(entityName, parsedQuery);
        net.sf.jsqlparser.schema.Table mainEntityTable;
        if (mainEntityAlias != null) {
            mainEntityTable = new net.sf.jsqlparser.schema.Table(null, mainEntityAlias.getName());
        } else {
            mainEntityTable = new net.sf.jsqlparser.schema.Table();
        }
        for (int i = 0; i < keyProperties.length; i++) {
            PropertyAccessor propertyAccessor = keyProperties[i];
            EqualsTo condition = new EqualsTo();
            parsedQuery.setWhere(new AndExpression(condition, new Parenthesis(parsedQuery.getWhere())));
            net.sf.jsqlparser.schema.Column column = new net.sf.jsqlparser.schema.Column(mainEntityTable, propertyAccessor.getName());
            condition.setLeftExpression(column);
            JdbcNamedParameter jdbcParameter = new JdbcNamedParameter();
            jdbcParameter.setName("p" + (p + i + 1));
            condition.setRightExpression(jdbcParameter);
            parameters[p + i] = propertyAccessor.get(pk);
        }
        String fullQueryString = parsedQuery.toString();
        if (fullQueryString.toLowerCase().startsWith(FAKE_SELECT_PREFIX)) {
            fullQueryString = fullQueryString.substring(FAKE_SELECT_PREFIX.length());
        }
        Session session = persistence.getSession(database);
        result = runHqlQuery(session, fullQueryString, parameters);
        if (result != null && !result.isEmpty()) {
            return result.get(0);
        } else {
            return null;
        }
    } catch (JSQLParserException e) {
        throw new Error(e);
    }
}
Also used : JdbcNamedParameter(net.sf.jsqlparser.expression.JdbcNamedParameter) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) CCJSqlParserManager(net.sf.jsqlparser.parser.CCJSqlParserManager) PropertyAccessor(com.manydesigns.elements.reflection.PropertyAccessor) JSQLParserException(net.sf.jsqlparser.JSQLParserException) OgnlHqlFormat(com.manydesigns.elements.text.OgnlHqlFormat) Alias(net.sf.jsqlparser.expression.Alias) EqualsTo(net.sf.jsqlparser.expression.operators.relational.EqualsTo) Session(org.hibernate.Session)

Example 3 with OgnlHqlFormat

use of com.manydesigns.elements.text.OgnlHqlFormat in project Portofino by ManyDesigns.

the class QueryUtils method mergeQuery.

/**
 * Merges a HQL query string with a {@link TableCriteria} object representing a search. The query string
 * is processed with an {@link OgnlSqlFormat}, so it can access values from the OGNL context, as well as
 * from an (optional) rootFactory object.
 * @param queryString the base query
 * @param criteria the criteria to merge with the query
 * @param rootObject the OGNL rootFactory object (can be null)
 * @return the merged query
 */
public static QueryStringWithParameters mergeQuery(String queryString, @Nullable TableCriteria criteria, Object rootObject) {
    OgnlHqlFormat hqlFormat = OgnlHqlFormat.create(queryString);
    String formatString = hqlFormat.getFormatString();
    Object[] parameters = hqlFormat.evaluateOgnlExpressions(rootObject);
    CCJSqlParserManager parserManager = new CCJSqlParserManager();
    PlainSelect parsedQueryString;
    PlainSelect parsedCriteriaQuery;
    try {
        parsedQueryString = parseQuery(parserManager, formatString);
    } catch (JSQLParserException e) {
        throw new RuntimeException("Couldn't merge query", e);
    }
    Alias mainEntityAlias = null;
    if (criteria != null) {
        mainEntityAlias = getEntityAlias(criteria.getTable().getActualEntityName(), parsedQueryString);
    }
    QueryStringWithParameters criteriaQuery = getQueryStringWithParametersForCriteria(criteria, mainEntityAlias != null ? mainEntityAlias.getName() : null, parameters.length + 1);
    String criteriaQueryString = criteriaQuery.getQueryString();
    Object[] criteriaParameters = criteriaQuery.getParameters();
    try {
        if (StringUtils.isEmpty(criteriaQueryString)) {
            parsedCriteriaQuery = new PlainSelect();
        } else {
            parsedCriteriaQuery = parseQuery(parserManager, criteriaQueryString);
        }
    } catch (JSQLParserException e) {
        throw new RuntimeException("Couldn't merge query", e);
    }
    Expression whereExpression;
    if (parsedQueryString.getWhere() != null) {
        if (parsedCriteriaQuery.getWhere() != null) {
            whereExpression = parsedQueryString.getWhere();
            if (!(whereExpression instanceof Parenthesis)) {
                whereExpression = new Parenthesis(whereExpression);
            }
            whereExpression = new AndExpression(whereExpression, parsedCriteriaQuery.getWhere());
        } else {
            whereExpression = parsedQueryString.getWhere();
        }
    } else {
        whereExpression = parsedCriteriaQuery.getWhere();
    }
    parsedQueryString.setWhere(whereExpression);
    if (criteria != null && criteria.getOrderBy() != null) {
        List orderByElements = new ArrayList();
        OrderByElement orderByElement = new OrderByElement();
        orderByElement.setAsc(criteria.getOrderBy().isAsc());
        String propertyName = criteria.getOrderBy().getPropertyAccessor().getName();
        if (mainEntityAlias != null) {
            propertyName = mainEntityAlias.getName() + "." + propertyName;
        }
        orderByElement.setExpression(new net.sf.jsqlparser.schema.Column(new net.sf.jsqlparser.schema.Table(), propertyName));
        orderByElements.add(orderByElement);
        if (parsedQueryString.getOrderByElements() != null) {
            for (Object el : parsedQueryString.getOrderByElements()) {
                OrderByElement toAdd = (OrderByElement) el;
                if (toAdd.getExpression() instanceof net.sf.jsqlparser.schema.Column) {
                    net.sf.jsqlparser.schema.Column column = (net.sf.jsqlparser.schema.Column) toAdd.getExpression();
                    if (StringUtils.isEmpty(column.getTable().getName()) && propertyName.equals(column.getColumnName())) {
                        // do not add
                        continue;
                    }
                }
                orderByElements.add(toAdd);
            }
        }
        parsedQueryString.setOrderByElements(orderByElements);
    }
    String fullQueryString = parsedQueryString.toString();
    if (fullQueryString.toLowerCase().startsWith(FAKE_SELECT_PREFIX)) {
        fullQueryString = fullQueryString.substring(FAKE_SELECT_PREFIX.length());
    }
    // merge the parameters
    ArrayList<Object> mergedParametersList = new ArrayList<Object>();
    mergedParametersList.addAll(Arrays.asList(parameters));
    mergedParametersList.addAll(Arrays.asList(criteriaParameters));
    Object[] mergedParameters = new Object[mergedParametersList.size()];
    mergedParametersList.toArray(mergedParameters);
    return new QueryStringWithParameters(fullQueryString, mergedParameters);
}
Also used : JSQLParserException(net.sf.jsqlparser.JSQLParserException) Parenthesis(net.sf.jsqlparser.expression.Parenthesis) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) QueryStringWithParameters(com.manydesigns.elements.text.QueryStringWithParameters) AndExpression(net.sf.jsqlparser.expression.operators.conditional.AndExpression) Expression(net.sf.jsqlparser.expression.Expression) OgnlHqlFormat(com.manydesigns.elements.text.OgnlHqlFormat) Alias(net.sf.jsqlparser.expression.Alias) CCJSqlParserManager(net.sf.jsqlparser.parser.CCJSqlParserManager)

Example 4 with OgnlHqlFormat

use of com.manydesigns.elements.text.OgnlHqlFormat in project Portofino by ManyDesigns.

the class QueryUtils method getObjects.

/**
 * Runs a query against the database. The query is processed with an {@link OgnlSqlFormat}, so it can
 * access values from the OGNL context, as well as from an (optional) rootFactory object.
 * @param session the session
 * @param queryString the query
 * @param rootObject the rootFactory object passed to the ognl evaluator (can be null).
 * @param firstResult index of the first result to return
 * @param maxResults maximum number of results to return
 * @return at most <code>maxResults</code> results from the query
 */
public static List<Object> getObjects(Session session, String queryString, Object rootObject, @Nullable Integer firstResult, @Nullable Integer maxResults) {
    OgnlHqlFormat hqlFormat = OgnlHqlFormat.create(queryString);
    String formatString = hqlFormat.getFormatString();
    Object[] parameters = hqlFormat.evaluateOgnlExpressions(rootObject);
    return runHqlQuery(session, formatString, parameters, firstResult, maxResults);
}
Also used : OgnlHqlFormat(com.manydesigns.elements.text.OgnlHqlFormat)

Aggregations

OgnlHqlFormat (com.manydesigns.elements.text.OgnlHqlFormat)4 JSQLParserException (net.sf.jsqlparser.JSQLParserException)2 Alias (net.sf.jsqlparser.expression.Alias)2 Parenthesis (net.sf.jsqlparser.expression.Parenthesis)2 AndExpression (net.sf.jsqlparser.expression.operators.conditional.AndExpression)2 CCJSqlParserManager (net.sf.jsqlparser.parser.CCJSqlParserManager)2 PropertyAccessor (com.manydesigns.elements.reflection.PropertyAccessor)1 QueryStringWithParameters (com.manydesigns.elements.text.QueryStringWithParameters)1 TableAccessor (com.manydesigns.portofino.reflection.TableAccessor)1 Expression (net.sf.jsqlparser.expression.Expression)1 JdbcNamedParameter (net.sf.jsqlparser.expression.JdbcNamedParameter)1 EqualsTo (net.sf.jsqlparser.expression.operators.relational.EqualsTo)1 Session (org.hibernate.Session)1