Search in sources :

Example 6 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor 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 7 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class QueryUtils method getObjectByPk.

/**
 * Loads an object by primary key.
 * @param persistence the persistence object
 * @param database the database (connection provider) to use
 * @param entityName the name of the entity to load - usually the normalized (lowercased, etc.) table name.
 * @param pk the primary key object. Might be an atomic value (String, Integer, etc.) for single-column primary
 * keys, or a composite object for multi-column primary keys.
 * @return the loaded object, or null if an object with that key does not exist.
 */
public static Object getObjectByPk(Persistence persistence, String database, String entityName, Serializable pk) {
    Session session = persistence.getSession(database);
    TableAccessor table = persistence.getTableAccessor(database, entityName);
    return getObjectByPk(session, table, pk);
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) Session(org.hibernate.Session)

Example 8 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class ManyToManyAction method createSelectionProviderFromHql.

public DefaultSelectionProvider createSelectionProviderFromHql(String name, String databaseName, String hql, DisplayMode dm, SearchDisplayMode sdm) {
    Database database = DatabaseLogic.findDatabaseByName(persistence.getModel(), databaseName);
    Table table = QueryUtils.getTableFromQueryString(database, hql);
    String entityName = table.getActualEntityName();
    Session session = persistence.getSession(databaseName);
    Collection<Object> objects = QueryUtils.getObjects(session, hql, null, null);
    TableAccessor tableAccessor = persistence.getTableAccessor(databaseName, entityName);
    ShortName shortNameAnnotation = tableAccessor.getAnnotation(ShortName.class);
    TextFormat[] textFormats = null;
    // L'ordinamento e' usato solo in caso di chiave singola
    if (shortNameAnnotation != null && tableAccessor.getKeyProperties().length == 1) {
        textFormats = new TextFormat[] { OgnlTextFormat.create(shortNameAnnotation.value()) };
    }
    DefaultSelectionProvider selectionProvider = SelectionProviderLogic.createSelectionProvider(name, objects, tableAccessor.getKeyProperties(), textFormats);
    selectionProvider.setDisplayMode(dm);
    selectionProvider.setSearchDisplayMode(sdm);
    return selectionProvider;
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) TextFormat(com.manydesigns.elements.text.TextFormat) OgnlTextFormat(com.manydesigns.elements.text.OgnlTextFormat) JSONObject(org.json.JSONObject) ShortName(com.manydesigns.elements.annotations.ShortName) Session(org.hibernate.Session)

Example 9 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class ManyToManyAction method init.

@Override
public Object init() {
    preparePage();
    if (m2mConfiguration == null || m2mConfiguration.getActualRelationTable() == null || m2mConfiguration.getActualManyTable() == null) {
        logger.error("Configuration is null or relation/many table not found (check previous log messages)");
        // TODO WebApplicationException instead?
        return this;
    }
    Table table = m2mConfiguration.getActualRelationTable();
    relationTableAccessor = new TableAccessor(table);
    manyTableAccessor = new TableAccessor(m2mConfiguration.getActualManyTable());
    if (StringUtils.isBlank(m2mConfiguration.getActualOnePropertyName())) {
        logger.error("One property name not set");
        return this;
    }
    String expression = m2mConfiguration.getOneExpression();
    if (!StringUtils.isBlank(expression)) {
        // Set primary key
        OgnlContext ognlContext = ElementsThreadLocals.getOgnlContext();
        // TODO handle exception
        onePk = OgnlUtils.getValueQuietly(expression, ognlContext, this);
        correctlyConfigured = true;
    } else {
        assert !StringUtils.isBlank(m2mConfiguration.getActualOnePropertyName());
        // Setup "one" selection
        SelectionProviderReference oneSelectionProvider = m2mConfiguration.getOneSelectionProvider();
        if (oneSelectionProvider != null) {
            ModelSelectionProvider actualSelectionProvider = oneSelectionProvider.getActualSelectionProvider();
            if (!(actualSelectionProvider instanceof DatabaseSelectionProvider)) {
                logger.warn("Selection provider {} not supported", actualSelectionProvider);
                return this;
            }
            TableAccessor tableAccessor = new TableAccessor(m2mConfiguration.getActualRelationTable());
            PropertyAccessor onePkAccessor = null;
            try {
                onePkAccessor = tableAccessor.getProperty(m2mConfiguration.getActualOnePropertyName());
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            }
            if (onePkAccessor == null) {
                logger.warn("Not a property: {}", m2mConfiguration.getActualOnePropertyName());
                return this;
            }
            String databaseName = m2mConfiguration.getActualOneDatabase().getDatabaseName();
            DatabaseSelectionProvider sp = (DatabaseSelectionProvider) actualSelectionProvider;
            DefaultSelectionProvider selectionProvider;
            String name = sp.getName();
            String hql = sp.getHql();
            if (StringUtils.isNotEmpty(hql)) {
                selectionProvider = createSelectionProviderFromHql(name, databaseName, hql, DisplayMode.DROPDOWN, SearchDisplayMode.DROPDOWN);
                if (sp instanceof ForeignKey) {
                    selectionProvider.sortByLabel();
                }
            } else {
                logger.warn("ModelSelection provider '{}': unsupported query", name);
                return this;
            }
            Object myInstance = tableAccessor.newInstance();
            oneSelectField = new SelectField(onePkAccessor, selectionProvider, Mode.EDIT, "__");
            oneSelectField.setRequired(false);
            oneSelectField.readFromRequest(context.getRequest());
            oneSelectField.writeToObject(myInstance);
            onePk = onePkAccessor.get(myInstance);
            correctlyConfigured = true;
        }
    }
    return this;
}
Also used : PropertyAccessor(com.manydesigns.elements.reflection.PropertyAccessor) SelectField(com.manydesigns.elements.fields.SelectField) OgnlContext(ognl.OgnlContext) TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) SelectionProviderReference(com.manydesigns.portofino.resourceactions.m2m.configuration.SelectionProviderReference) JSONObject(org.json.JSONObject)

Example 10 with TableAccessor

use of com.manydesigns.portofino.reflection.TableAccessor in project Portofino by ManyDesigns.

the class PersistenceTest method testSearchAndReadCategorieProdotti.

public void testSearchAndReadCategorieProdotti() {
    Session session = persistence.getSession("jpetstore");
    CriteriaQuery criteria = QueryUtils.createCriteria(session, "category").query;
    List resultCat = new ArrayList(session.createQuery(criteria).list());
    int sizeCat = resultCat.size();
    assertEquals("categorie", 5, sizeCat);
    resultCat.forEach(cat -> {
        assertNotNull(get(cat, "name"));
    });
    criteria = QueryUtils.createCriteria(session, "product").query;
    List resultProd = new ArrayList(session.createQuery(criteria).list());
    Table table = DatabaseLogic.findTableByName(persistence.getModel(), "jpetstore", "PUBLIC", "CATEGORY");
    TableAccessor tableAccessor = new TableAccessor(table);
    TableCriteria tableCriteria = new TableCriteria(table);
    findCategory(tableAccessor, tableCriteria);
    int sizePrd = resultProd.size();
    assertEquals("prodotti", 16, sizePrd);
    Object prd0 = resultProd.get(0);
    assertEquals("FI-SW-01", get(prd0, "productid"));
    assertEquals("Angelfish", get(prd0, "name"));
}
Also used : TableAccessor(com.manydesigns.portofino.reflection.TableAccessor) TableCriteria(com.manydesigns.portofino.persistence.TableCriteria) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) FileObject(org.apache.commons.vfs2.FileObject) Session(org.hibernate.Session)

Aggregations

TableAccessor (com.manydesigns.portofino.reflection.TableAccessor)12 Session (org.hibernate.Session)9 TableCriteria (com.manydesigns.portofino.persistence.TableCriteria)4 PropertyAccessor (com.manydesigns.elements.reflection.PropertyAccessor)3 FileObject (org.apache.commons.vfs2.FileObject)3 ShortName (com.manydesigns.elements.annotations.ShortName)2 OgnlTextFormat (com.manydesigns.elements.text.OgnlTextFormat)2 QueryStringWithParameters (com.manydesigns.elements.text.QueryStringWithParameters)2 TextFormat (com.manydesigns.elements.text.TextFormat)2 JSONObject (org.json.JSONObject)2 SelectField (com.manydesigns.elements.fields.SelectField)1 OgnlHqlFormat (com.manydesigns.elements.text.OgnlHqlFormat)1 Model (com.manydesigns.portofino.model.Model)1 ConfigurationClass (com.manydesigns.portofino.resourceactions.annotations.ConfigurationClass)1 SelectionProviderReference (com.manydesigns.portofino.resourceactions.m2m.configuration.SelectionProviderReference)1 Serializable (java.io.Serializable)1 BigInteger (java.math.BigInteger)1 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)1 JSQLParserException (net.sf.jsqlparser.JSQLParserException)1 Alias (net.sf.jsqlparser.expression.Alias)1