Example usage for org.hibernate Query getReturnAliases

List of usage examples for org.hibernate Query getReturnAliases

Introduction

In this page you can find the example usage for org.hibernate Query getReturnAliases.

Prototype

@Deprecated
String[] getReturnAliases();

Source Link

Usage

From source file:com.jaspersoft.ireport.designer.connection.JRSpringLoadedHibernateConnection.java

License:Open Source License

@Override
public void test() throws Exception {
    try {/*  w ww .  java  2  s  .  co m*/
        Thread.currentThread().setContextClassLoader(IReportManager.getInstance().getReportClassLoader());

        SessionFactory sf = getSessionFactory();
        if (sf == null) {
            JOptionPane.showMessageDialog(Misc.getMainWindow(),
                    //I18n.getString("messages.connectionDialog.noSessionFactoryReturned",
                    "No session factory returned.  Check your session factory bean id against the spring configuration.",
                    "Error", JOptionPane.ERROR_MESSAGE);
        } else {

            Session hb_session = sf.openSession();
            Transaction transaction = hb_session.beginTransaction();
            Query q = hb_session.createQuery("select address as address Address as address");

            q.setFetchSize(1);
            java.util.Iterator iterator = q.iterate();
            // this is a stupid thing: iterator.next();

            String[] aliases = q.getReturnAliases();
            Type[] types = q.getReturnTypes();

            JOptionPane.showMessageDialog(Misc.getMainWindow(),
                    //I18n.getString("messages.connectionDialog.hibernateConnectionTestSuccessful",
                    "iReport successfully created a Hibernate session factory from your Spring configuration.",
                    "", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (Exception e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(Misc.getMainWindow(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);

    }
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.hibernate.HQLFieldsReader.java

License:Open Source License

public Vector readFields() throws Exception {
    prepareQuery();//from  w  w  w.j ava  2s .c om

    SessionFactory hb_sessionFactory = null;
    Session hb_session = null;
    Transaction transaction = null;

    notScalars.clear();

    try {
        IReportConnection conn = IReportManager.getInstance().getDefaultConnection();
        if (!(conn instanceof JRHibernateConnection)) {
            throw new Exception("No Hibernate connection selected.");
        }

        hb_session = ((JRHibernateConnection) conn).createSession();

        if (hb_session == null) {
            throw new Exception("Problem creating the Session object for Hibernate");
        }

        transaction = hb_session.beginTransaction();
        Query q = hb_session.createQuery(getQueryString());

        Iterator paramIterator = queryParameters.keySet().iterator();

        while (paramIterator.hasNext()) {
            String hqlParamName = "" + paramIterator.next();
            setParameter(hb_session, q, hqlParamName, queryParameters.get(hqlParamName));
        }

        q.setFetchSize(1);
        java.util.Iterator iterator = q.iterate();
        // this is a stupid thing: iterator.next();

        String[] aliases = q.getReturnAliases();
        Type[] types = q.getReturnTypes();

        Vector fields = new Vector();

        for (int i = 0; i < types.length; ++i) {
            if (types[i].isComponentType() || types[i].isEntityType()) {

                // look for alias...
                String aliasName = null;
                if (aliases != null && aliases.length > i && !aliases[i].equals(i + "")) {
                    aliasName = aliases[i];
                    JRDesignField field = new JRDesignField();
                    field.setName(aliases[i]);

                    Class clazzRT = types[i].getReturnedClass();

                    if (clazzRT.isPrimitive()) {
                        clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                    }

                    String returnType = clazzRT.getName();

                    field.setValueClassName(returnType);
                    field.setDescription(aliases[i]);
                    fields.add(field);
                }

                // look for fields like for a javabean...
                java.beans.PropertyDescriptor[] pd = org.apache.commons.beanutils.PropertyUtils
                        .getPropertyDescriptors(types[i].getReturnedClass());

                if (aliasName != null) {
                    notScalars.add(new FieldClassWrapper(aliasName, types[i].getReturnedClass().getName()));
                } else {
                    notScalars.add(types[i].getReturnedClass().getName());
                }

                for (int nd = 0; nd < pd.length; ++nd) {
                    String fieldName = pd[nd].getName();
                    if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null) {
                        if (fieldName.equals("class"))
                            continue;

                        Class clazzRT = pd[nd].getPropertyType();

                        if (clazzRT.isPrimitive()) {
                            clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                        }

                        String returnType = clazzRT.getName();

                        JRDesignField field = new JRDesignField();
                        field.setName(fieldName);
                        field.setValueClassName(returnType);

                        if (types.length > 1 && aliasName != null) {
                            fieldName = aliasName + "." + fieldName;
                            field.setDescription(fieldName); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
                            field.setName(fieldName);
                        }
                        fields.add(field);
                    }
                }

            } else {
                String fieldName = types[i].getName();
                if (aliases != null && aliases.length > i && !aliases[i].equals("" + i))
                    fieldName = aliases[i];

                Class clazzRT = types[i].getReturnedClass();

                if (clazzRT.isPrimitive()) {
                    clazzRT = MethodUtils.getPrimitiveWrapper(clazzRT);
                }
                String returnType = clazzRT.getName();

                JRDesignField field = new JRDesignField();
                field.setName(fieldName);
                field.setValueClassName(returnType);
                //field.setDescription("");
                fields.add(field);
            }
        }
        /*
        else
        {
            for (int i =0; i<types.length; ++i)
            {
                if (aliases != null && aliases.length > 0 && !aliases[0].equals(""+i))
                {
                    JRField field = new JRField(aliases[i], types[i].getReturnedClass().getName());
                    field.setDescription("The whole entity/component object");
                    fields.add(field);
                            
                            
                }
                        
                        
            //    out.println(types[i].getName() + " " + types[i].getReturnedClass().getName() +  "<br>");
            }
        }
         */

        return fields;

    } catch (Exception ex) {
        ex.printStackTrace();
        throw ex;
    } finally {

        if (transaction != null)
            try {
                transaction.rollback();
            } catch (Exception ex) {
            }
        if (hb_session != null)
            try {
                hb_session.close();
            } catch (Exception ex) {
            }
    }
}

From source file:com.qcadoo.model.internal.HibernateServiceImpl.java

License:Open Source License

@Override
public InternalDataDefinition resolveDataDefinition(final Query query) {
    return resolveDataDefinition(query.getReturnTypes(), query.getReturnAliases());
}

From source file:com.wavemaker.runtime.data.hibernate.DataServiceMetaData_Hib.java

License:Open Source License

private DataOperationFactory initFactory(final Session session) {
    return new DataOperationFactory() {

        // this is magic, and has to match the name of the
        // generated example query(ies).
        private static final String GENERATED_QUERY_NAME = "ExampleHQLQuery1";

        @Override//from  w w  w .  j a  v a2  s .  c om
        public Collection<String> getEntityClassNames() {
            return DataServiceMetaData_Hib.this.entityClassNames;
        }

        @Override
        public List<Tuple.Three<String, String, Boolean>> getQueryInputs(String queryName) {

            List<Tuple.Three<String, String, Boolean>> rtn = new ArrayList<Tuple.Three<String, String, Boolean>>();

            NamedQueryDefinition def = getQueryDefinition(queryName);

            Map<String, String> m = CastUtils.cast(def.getParameterTypes());

            for (Map.Entry<String, String> e : m.entrySet()) {
                Tuple.Two<String, Boolean> t = DataServiceUtils.getQueryType(e.getValue());
                rtn.add(Tuple.tuple(e.getKey(), t.v1, t.v2));
            }

            return rtn;
        }

        @Override
        @SuppressWarnings("unchecked")
        public Collection<String> getQueryNames() {

            Collection<String> rtn = new HashSet<String>();

            Configuration cfg = getConfiguration();

            rtn.addAll(cfg.getNamedQueries().keySet());
            rtn.addAll(cfg.getNamedSQLQueries().keySet());

            return rtn;
        }

        @Override
        public List<String> getQueryReturnNames(String operationName, String queryName) {

            Query query = session.getNamedQuery(queryName);

            try {
                String[] names = query.getReturnAliases();
                if (names != null) {
                    return Arrays.asList(names);
                }
            } catch (RuntimeException ex) {
            }

            return Collections.emptyList();

        }

        @Override
        public boolean requiresResultWrapper(String operationName, String queryName) {
            NamedQueryDefinition query = getQueryDefinition(queryName);
            return DataServiceUtils.requiresResultWrapper(query.getQuery());
        }

        @Override
        public List<String> getQueryReturnTypes(String operationName, String queryName) {

            List<String> rtn = new ArrayList<String>();

            Type[] rtnTypes = getReturnTypes(queryName);

            String queryString = getQueryDefinition(queryName).getQuery();

            if (rtnTypes == null) {
                // Must be DML
                if (!DataServiceUtils.isDML(queryString)) {
                    // throw new AssertionError(
                    // "Query " + queryName + " doesn't return anything");
                    // actually if it is a sql query we also end up here -
                    // the tests have at least one...
                }
                rtn.add(DataServiceConstants.DML_OPERATION_RTN_TYPE.getName());
            } else {

                if (DataServiceUtils.isDynamicInstantiationQuery(queryString)) {
                    String className = DataServiceUtils.getDynamicInstantiationClassName(queryString);

                    if (!StringUtils.isFullyQualified(className)) {
                        if (DataServiceMetaData_Hib.this.entityNames.contains(className)) {
                            className = StringUtils.fq(getDataPackage(), className);
                        }
                    }
                    rtn.add(className);
                } else {
                    for (Type t : rtnTypes) {
                        rtn.add(getJavaTypeName(t));
                    }
                }
            }

            return rtn;
        }

        @Override
        public boolean queryReturnsSingleResult(String operationName, String queryName) {

            // hack for generated queries - only required for initial
            // ServiceDefinition instance that is used to add the service
            if (queryName.equals(GENERATED_QUERY_NAME)) {
                return true;
            }

            // to make existing tests happy
            if (queryName.startsWith("get") && queryName.endsWith("ById")) {
                return true;
            }

            return false;
        }

        private Type[] getReturnTypes(String queryName) {

            Type[] rtn = null;

            Query query = session.getNamedQuery(queryName);

            // this blows up for named sql queries (vs named hql queries)
            // exception msg from hibernate is: "not yet implemented for sql
            // queries"
            try {
                rtn = query.getReturnTypes();
            } catch (RuntimeException ex) {
                if (DataServiceLoggers.metaDataLogger.isDebugEnabled()) {
                    DataServiceLoggers.metaDataLogger
                            .debug("Failed to determine rtn type for query \"" + queryName + "\"");
                }
            }
            return rtn;
        }
    };
}

From source file:com.wavemaker.runtime.data.task.CheckQueryTask.java

License:Open Source License

private void checkQueryReturnAliases(Query query) {

    if (query.getReturnAliases() == null) {
        return;/* w w w  . j a va 2 s .co  m*/
    }

    Collection<String> upperCaseAliases = new ArrayList<String>();
    Collection<String> illegalIdentifiers = new ArrayList<String>();

    Type[] types = query.getReturnTypes();

    List<String> names = DataServiceUtils.getColumnNames(types.length, Arrays.asList(query.getReturnAliases()));

    for (String name : names) {
        if (Character.isUpperCase(name.charAt(0))) {
            upperCaseAliases.add(name);
        }
        if (!StringUtils.isValidJavaIdentifier(name)) {
            illegalIdentifiers.add(name);
        }
    }
    if (!upperCaseAliases.isEmpty()) {
        throw new DataServiceQueryException("Query return aliases cannot start with upper-case letters: "
                + ObjectUtils.toString(upperCaseAliases));
    }
    if (!illegalIdentifiers.isEmpty()) {
        throw new DataServiceQueryException("Query return aliases must be legal java identifiers: "
                + ObjectUtils.toString(illegalIdentifiers));
    }
}

From source file:com.wavemaker.runtime.data.task.NamedQueryTask.java

License:Open Source License

private Object marshalIntoCustomType(String queryName, DataServiceMetaData meta, Query query, Object rtn) {

    Type[] types = query.getReturnTypes();
    String[] returnAliases = query.getReturnAliases();

    if (returnAliases == null) {
        returnAliases = new String[] {};
    }/*from   w  w  w  . j  a  va  2  s .  c  om*/

    List<String> propertyNames = DataServiceUtils.getColumnNames(types.length, Arrays.asList(returnAliases));

    @SuppressWarnings("unchecked")
    List<Object> rows = (List<Object>) rtn;

    List<Object> newRtn = new ArrayList<Object>(rows.size());

    ObjectAccess oa = getObjectAccess();

    for (Object o : rows) {
        Object bean = instantiateOutputType(meta.getDataPackage(), queryName);
        newRtn.add(bean);
        if (o instanceof Object[]) {
            Object[] row = (Object[]) o;
            if (row.length != propertyNames.size()) {
                throw new AssertionError("Number of columns doesn't match");
            }
            int i = 0;
            for (Object col : row) {
                oa.setProperty(bean, propertyNames.get(i++), col);
            }
        } else {
            if (propertyNames.size() != 1) {
                throw new AssertionError("Expected single column");
            }
            oa.setProperty(bean, propertyNames.get(0), o);
        }
    }

    return newRtn;

}

From source file:de.innovationgate.webgate.api.jdbc.WGLanguageChoosingHQLResultSet.java

License:Open Source License

public WGLanguageChoosingHQLResultSet(WGDatabaseImpl wgDatabaseImpl, Query hibQuery,
        Map<String, Object> queryParameters, Map<String, Object> queryOptions, List<WGLanguage> queryLanguages)
        throws WGBackendException {
    super(wgDatabaseImpl, hibQuery, queryParameters, queryOptions);
    try {//  w w  w . j a  v  a2 s  .co  m

        String[] queryAliases = hibQuery.getReturnAliases();
        if (queryAliases != null) {
            _columnNames = Arrays.asList(queryAliases);
        }

        long timeBefore = System.currentTimeMillis();

        _contents = getQuery().list();

        // Build maps per page
        Map<Object, Map<String, WGContentKey>> pages = new HashMap<Object, Map<String, WGContentKey>>();
        for (WGContentKey key : _contents) {
            Map<String, WGContentKey> pageMap = pages.get(key.getStructKey());
            if (pageMap == null) {
                pageMap = new HashMap<String, WGContentKey>();
                pages.put(key.getStructKey(), pageMap);
            }
            pageMap.put(key.getLanguage(), key);
        }

        // Choose content versions to return
        List<WGContentKey> contentsToReturn = new ArrayList<WGContentKey>();
        for (Map<String, WGContentKey> pageMap : pages.values()) {
            WGContentKey chosenContent = null;
            if (pageMap.size() == 1) {
                chosenContent = pageMap.values().iterator().next();
            } else {
                for (WGLanguage lang : queryLanguages) {
                    WGContentKey conKey = pageMap.get(lang.getName());
                    if (conKey != null) {
                        chosenContent = conKey;
                        break;
                    }
                }
            }
            if (chosenContent != null) {
                contentsToReturn.add(chosenContent);
            }
        }

        // Keep only chosen ones in the contents list
        _contents.retainAll(contentsToReturn);

        long timeAfter = System.currentTimeMillis();
        setExecutionTime(timeAfter - timeBefore);
    } catch (WGNotSupportedException e) {
        throw new WGBackendException("Exception creating language choosing resultset", e);
    } catch (WGAPIException e) {
        throw new WGBackendException("Exception creating language choosing resultset", e);
    }

}

From source file:de.innovationgate.webgate.api.jdbc.WGLazyHQLResultSet.java

License:Open Source License

public WGLazyHQLResultSet(WGDatabaseImpl parent, Query query, Map<String, Object> queryParameters,
        Map<String, Object> queryOptions) throws WGAPIException {
    super(parent, query, queryParameters, queryOptions);

    String[] queryAliases = query.getReturnAliases();
    if (queryAliases != null) {
        _columnNames = Arrays.asList(queryAliases);
    }/*w  w  w. j av a 2  s  .com*/
}

From source file:de.innovationgate.webgate.api.jdbc.WGStraightHQLResultSet.java

License:Open Source License

public WGStraightHQLResultSet(WGDatabaseImpl parent, Query query, Map<String, Object> queryParameters,
        Map<String, Object> queryOptions) throws WGAPIException {
    super(parent, query, queryParameters, queryOptions);

    String[] queryAliases = query.getReturnAliases();
    if (queryAliases != null) {
        _columnNames = Arrays.asList(queryAliases);
    }/*from   w  ww  .j a  va  2  s .co  m*/
}

From source file:net.databinder.components.hib.QueryPanel.java

License:Open Source License

/**
 * Creates a result table for the current query.
 * @return a result table, or an empty label if there is no current query
 *///from w  w w  .  ja  va  2 s.c om
private Component getResultsTable() {
    if (Strings.isEmpty(query.getQuery())) {
        return new Label("results", "");
    } else {
        IDataProvider dataProvider = new IDataProvider() {
            private static final long serialVersionUID = 1L;

            public void detach() {
            }

            public int size() {
                Session sess = Databinder.getHibernateSession();
                Query query = sess.createQuery(getQuery());
                return query.list().size();
            }

            public String getQuery() {
                return QueryPanel.this.query.getQuery();
            }

            public IModel model(Object object) {
                return new BoundCompoundPropertyModel(new HibernateObjectModel(object));
            }

            public Iterator iterator(int first, int count) {
                Session sess = Databinder.getHibernateSession();
                long start = System.nanoTime();
                try {
                    Query q = sess.createQuery(getQuery());
                    q.setFirstResult(first);
                    q.setMaxResults(count);
                    return q.iterate();
                } finally {
                    float nanoTime = ((System.nanoTime() - start) / 1000) / 1000.0f;
                    setExecutionInfo("query executed in " + nanoTime + " ms: " + getQuery());
                }
            }
        };
        IColumn[] columns;
        Session sess = Databinder.getHibernateSession();
        Query q = sess.createQuery(query.getQuery());
        String[] aliases;
        Type[] returnTypes;
        try {
            aliases = q.getReturnAliases();
            returnTypes = q.getReturnTypes();
        } catch (NullPointerException e) { // thrown on updates
            return new Label("results", "");
        }

        if (returnTypes.length != 1) {
            columns = new IColumn[returnTypes.length];
            for (int i = 0; i < returnTypes.length; i++) {
                String alias = aliases == null || aliases.length <= i ? returnTypes[i].getName() : aliases[i];
                final int index = i;
                columns[i] = new AbstractColumn(new Model(alias)) {
                    private static final long serialVersionUID = 1L;

                    public void populateItem(Item cellItem, String componentId, IModel rowModel) {
                        Object[] objects = (Object[]) rowModel.getObject();
                        cellItem.add(new Label(componentId,
                                new Model(objects[index] == null ? "" : objects[index].toString())));
                    }
                };
            }
        } else {
            Type returnType = returnTypes[0];
            if (returnType.isEntityType()) {
                Class clss = returnType.getReturnedClass();
                ClassMetadata metadata = Databinder.getHibernateSessionFactory().getClassMetadata(clss);
                List<IColumn> cols = new ArrayList<IColumn>();
                String idProp = metadata.getIdentifierPropertyName();
                cols.add(new PropertyColumn(new Model(idProp), idProp));
                String[] properties = metadata.getPropertyNames();
                for (String prop : properties) {
                    Type type = metadata.getPropertyType(prop);
                    if (type.isCollectionType()) {
                        // TODO: see if we could provide a link to the collection value
                    } else {
                        cols.add(new PropertyColumn(new Model(prop), prop));
                    }
                }
                columns = (IColumn[]) cols.toArray(new IColumn[cols.size()]);
            } else {
                String alias = aliases == null || aliases.length == 0 ? returnType.getName() : aliases[0];
                columns = new IColumn[] { new AbstractColumn(new Model(alias)) {
                    private static final long serialVersionUID = 1L;

                    public void populateItem(Item cellItem, String componentId, IModel rowModel) {
                        cellItem.add(new Label(componentId, rowModel));
                    }
                } };
            }
        }
        DataTable dataTable = new DataTable("results", columns, dataProvider, 10);

        dataTable.addTopToolbar(new HeadersToolbar(dataTable, null));
        dataTable.addBottomToolbar(new NavigationToolbar(dataTable));
        dataTable.setOutputMarkupId(true);
        return dataTable;
    }
}