Example usage for org.hibernate.criterion Projections projectionList

List of usage examples for org.hibernate.criterion Projections projectionList

Introduction

In this page you can find the example usage for org.hibernate.criterion Projections projectionList.

Prototype

public static ProjectionList projectionList() 

Source Link

Document

Create a new projection list.

Usage

From source file:com.algoTrader.PropertySearch.java

/**
 * Gets the total possible count of objects returned in this search.
 * @return totalCount/*from ww w  .  j a va  2 s.  c  o  m*/
 */
public int getTotalCount() {
    int count;
    if (this.search.isUseSqlLimiting()) {
        // Remove first result requirement
        this.getConfiguration().setFirstResult(new Integer(0));
        this.getRootCriteria().setProjection(Projections.projectionList().add(Projections.rowCount()));
        count = ((Integer) this.executeAsList().iterator().next()).intValue();
    } else {
        count = this.totalCount;
    }
    return count;
}

From source file:com.amalto.core.storage.hibernate.StandardQueryHandler.java

License:Open Source License

@Override
public StorageResults visit(Distinct distinct) {
    // Standard visit for the expression where distinct should be added
    distinct.getExpression().accept(this);
    // Wraps the last projection into a 'distinct' statement
    // Note: Hibernate does not provide projection editing functions... have to work around that with a new
    // projection list.
    ProjectionList newProjectionList = Projections.projectionList();
    int i = 0;/*from  w w w . j ava 2s  .  c o m*/
    for (; i < projectionList.getLength() - 1; i++) {
        newProjectionList.add(projectionList.getProjection(i));
    }
    newProjectionList.add(Projections.distinct(projectionList.getProjection(i)));
    projectionList = newProjectionList;
    return null;
}

From source file:com.amalto.core.storage.hibernate.StandardQueryHandler.java

License:Open Source License

protected Criteria createCriteria(Select select) {
    List<ComplexTypeMetadata> selectedTypes = select.getTypes();
    if (selectedTypes.isEmpty()) {
        throw new IllegalArgumentException("Select clause is expected to select at least one entity type."); //$NON-NLS-1$
    }/*from  w  w  w  . ja v a 2 s.  c om*/
    mainType = selectedTypes.get(0);
    String mainClassName = ClassCreator.getClassName(mainType.getName());
    criteria = session.createCriteria(mainClassName, mainType.getName());
    if (!select.forUpdate()) {
        criteria.setReadOnly(true); // We are reading data, turns on ready only mode.
    }
    // Handle JOIN (if any)
    List<Join> joins = select.getJoins();
    for (Join join : joins) {
        join.accept(this);
    }
    // If select is not a projection, selecting root type is enough, otherwise add projection for selected fields.
    if (select.isProjection()) {
        boolean toDistinct = true;
        projectionList = Projections.projectionList();
        {
            List<TypedExpression> queryFields = select.getSelectedFields();
            boolean isCountQuery = false;
            boolean hasGroupSize = false;
            for (Expression selectedField : queryFields) {
                if (selectedField instanceof GroupSize) {
                    hasGroupSize = true;
                }
                selectedField.accept(this);
                if (selectedField instanceof Alias) {
                    Alias alias = (Alias) selectedField;
                    if (alias.getTypedExpression() instanceof Count) {
                        isCountQuery = true;
                    }
                    if (alias.getTypedExpression() instanceof Distinct) {
                        toDistinct = false;
                    }
                }
            }
            // TMDM-9502/TMDM-10395, If selected fields including "GroupSize", besides GROUP BY "x_talend_task_id"
            // NOT ORACLE DB, should GROUP BY "All Key Fields"
            // ORACLE DB, need to GROUP BY "All Selected Fields"
            if (hasGroupSize) {
                projectionList = optimizeProjectionList(mainType, projectionList);
            }
            if (isCountQuery && queryFields.size() > 1) {
                Projection projection = projectionList.getProjection(projectionList.getLength() - 1);
                projectionList = Projections.projectionList();
                projectionList.add(projection);
                TypedExpression countTypedExpression = selectedFields.get(queryFields.size() - 1);
                selectedFields.clear();
                selectedFields.add(countTypedExpression);
            }
        }
        // for SELECT DISTINCT, ORDER BY expressions must appear in select list. Or it will throw exception in H2, postgres...
        for (OrderBy current : select.getOrderBy()) {
            if ((current.getExpression() instanceof Field
                    && !select.getSelectedFields().contains(current.getExpression()))
                    || current.getExpression() instanceof Type || current.getExpression() instanceof Alias) {
                toDistinct = false;
                break;
            }
        }
        if (select.getOrderBy().size() > 0 && toDistinct) {
            criteria.setProjection(Projections.distinct(projectionList));
        } else {
            criteria.setProjection(projectionList);
        }
    } else {
        // TMDM-5388: Hibernate sometimes returns duplicate results (like for User stored in System storage), this
        // line avoids this situation.
        criteria.setResultTransformer(DistinctRootEntityResultTransformer.INSTANCE);
    }
    // Make projection read only in case code tries to modify it later (see code that handles condition).
    projectionList = ReadOnlyProjectionList.makeReadOnly(projectionList);
    // Handle condition (if there's any condition to handle).
    Condition condition = select.getCondition();
    if (condition != null) {
        condition.accept(this);
    }
    // Order by
    for (OrderBy current : select.getOrderBy()) {
        if (current.getExpression() instanceof Count) {
            int limit = select.getPaging().getLimit();
            if (limit > 0) {
                RDBMSDataSource dataSource = (RDBMSDataSource) storage.getDataSource();
                if (dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.DB2
                        || dataSource.getDialectName() == RDBMSDataSource.DataSourceDialect.SQL_SERVER) {
                    LOGGER.error("The query is not supported by DB2 and SQLSERVER Database."); //$NON-NLS-1$
                    throw new UnsupportedQueryException(
                            "The query is not supported by DB2 and SQLSERVER Database."); //$NON-NLS-1$
                }
            }
        }
        current.accept(this);
    }
    return criteria;
}

From source file:com.amalto.core.storage.hibernate.StandardQueryHandler.java

License:Open Source License

private ProjectionList optimizeProjectionList(ComplexTypeMetadata mainType, ProjectionList oldProjectionList) {
    ProjectionList newProjectionList = null;
    RDBMSDataSource dataSource = (RDBMSDataSource) storage.getDataSource();
    if (dataSource.getDialectName() != RDBMSDataSource.DataSourceDialect.ORACLE_10G) {
        newProjectionList = oldProjectionList;
        for (FieldMetadata keyField : mainType.getKeyFields()) {
            newProjectionList.add(Projections.groupProperty(keyField.getName()));
        }/*ww  w. j  av  a 2 s.  com*/
    } else { // ORACLE need to GROUP BY all selected fields
        newProjectionList = Projections.projectionList();
        Set<String> groupBys = new LinkedHashSet<String>();// GROUP BY fields
        ProjectionList extraProjectionList = Projections.projectionList();
        for (int i = 0; i < oldProjectionList.getLength(); i++) {
            String propertyName = null;
            Projection oldProjection = oldProjectionList.getProjection(i);
            if (oldProjection instanceof SQLProjection) { // Group Size
                newProjectionList.add(oldProjection);
            } else if (oldProjection instanceof PropertyProjection) {// normal fields
                propertyName = ((PropertyProjection) oldProjection).getPropertyName();
                newProjectionList.add(Projections.groupProperty(propertyName));
            } else if (oldProjection instanceof AggregateProjection) {// Max, Min
                propertyName = ((AggregateProjection) oldProjection).getPropertyName();
                newProjectionList.add(oldProjection);
                extraProjectionList.add(Projections.groupProperty(propertyName));
            }
            if (propertyName != null) {
                groupBys.add(propertyName);
            }
        }
        // Add key fields to GROUP BY
        for (FieldMetadata keyField : mainType.getKeyFields()) {
            String keyFieldName = mainType.getName() + '.' + keyField.getName();
            if (!groupBys.contains(keyFieldName)) {
                extraProjectionList.add(Projections.groupProperty(keyFieldName));
            }
        }
        for (int i = 0; i < extraProjectionList.getLength(); i++) {
            newProjectionList.add(extraProjectionList.getProjection(i));
        }
    }
    return newProjectionList;
}

From source file:com.aquest.emailmarketing.web.dao.TrackingResponseDao.java

/**
 * Gets the no of opens by broadcast./*from  w w w .ja va 2s. c  om*/
 *
 * @param broadcast_id the broadcast_id
 * @return the no of opens by broadcast
 */
public int getNoOfOpensByBroadcast(String broadcast_id) {
    Criteria crit = session().createCriteria(TrackingResponse.class);
    crit.add(Restrictions.eq("broadcast_id", broadcast_id));
    crit.add(Restrictions.eq("response_type", "Open"));
    List result = crit.setProjection(Projections.projectionList().add(Projections.groupProperty("unique_id")))
            .list();
    return result.size();
}

From source file:com.aquest.emailmarketing.web.dao.TrackingResponseDao.java

/**
 * Gets the no of click by broadcast./*w w w.ja v  a 2  s.c o m*/
 *
 * @param broadcast_id the broadcast_id
 * @return the no of click by broadcast
 */
public int getNoOfClickByBroadcast(String broadcast_id) {
    Criteria crit = session().createCriteria(TrackingResponse.class);
    crit.add(Restrictions.eq("broadcast_id", broadcast_id));
    crit.add(Restrictions.eq("response_type", "Click"));
    List result = crit.setProjection(Projections.projectionList().add(Projections.groupProperty("unique_id")))
            .list();
    return result.size();
}

From source file:com.ar.dev.tierra.api.dao.impl.ProductoDAOImpl.java

@SuppressWarnings("unchecked")
@Override/*from  www.  j  a  va  2  s.  c o  m*/
public List<Producto> getAll() {
    Criteria criteria = getSession().createCriteria(Producto.class);
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.property("idProducto"), "idProducto");
    projList.add(Projections.property("marcas"), "marcas");
    projList.add(Projections.property("descripcion"), "descripcion");
    projList.add(Projections.property("colorProducto"), "colorProducto");
    projList.add(Projections.property("cantidadTotal"), "cantidadTotal");
    projList.add(Projections.property("talla"), "talla");
    criteria.add(Restrictions.eq("estadoProducto", true));
    criteria.addOrder(Order.desc("idProducto"));
    criteria.setProjection(Projections.distinct(projList));
    criteria.setResultTransformer(Transformers.aliasToBean(Producto.class));
    List<Producto> list = criteria.list();
    return list;
}

From source file:com.ar.dev.tierra.api.dao.impl.UsuariosDAOImpl.java

@SuppressWarnings("unchecked")
@Override//  w ww .ja  va2s  .  co  m
public List<Usuarios> allUsuarios() {
    Criteria criteria = getSession().createCriteria(Usuarios.class);
    criteria.addOrder(Order.asc("idUsuario"));
    ProjectionList projList = Projections.projectionList();
    projList.add(Projections.property("idUsuario"), "idUsuario");
    projList.add(Projections.property("roles"), "roles");
    projList.add(Projections.property("nombre"), "nombre");
    projList.add(Projections.property("apellido"), "apellido");
    projList.add(Projections.property("dni"), "dni");
    projList.add(Projections.property("telefono"), "telefono");
    projList.add(Projections.property("email"), "email");
    projList.add(Projections.property("fechaNacimiento"), "fechaNacimiento");
    projList.add(Projections.property("domicilio"), "domicilio");
    projList.add(Projections.property("estado"), "estado");
    projList.add(Projections.property("ultimaConexion"), "ultimaConexion");
    projList.add(Projections.property("usuarioSucursal"), "usuarioSucursal");
    criteria.setProjection(Projections.distinct(projList));
    criteria.setResultTransformer(Transformers.aliasToBean(Usuarios.class));
    List<Usuarios> us = criteria.list();
    return us;
}

From source file:com.ateam.hibernate.HibernateDAOImpl.java

public String checkRole(String strUserName, String password) throws DataAccessException, java.sql.SQLException {
    String obj = null;/*from  w  ww  .jav  a 2  s .c  o m*/
    DetachedCriteria critthree = DetachedCriteria.forClass(UserAttr.class);
    ProjectionList pl = Projections.projectionList();
    pl.add(Projections.groupProperty("userRole"));
    critthree.add(Restrictions.eq("userName", strUserName));
    critthree.add(Restrictions.eq("userPassword", password));
    critthree.setProjection(pl);
    List objs = getHibernateTemplate().findByCriteria(critthree);
    if ((objs != null) && (objs.size() > 0)) {
        obj = (String) objs.get(0);
    }
    return obj;
}

From source file:com.ateam.hibernate.HibernateDAOImpl.java

public String checkFullName(String strUserName, String password)
        throws DataAccessException, java.sql.SQLException {
    String obj = null;//from www . j  av a2s.  c  o  m
    DetachedCriteria critname = DetachedCriteria.forClass(UserAttr.class);
    ProjectionList pl = Projections.projectionList();
    pl.add(Projections.groupProperty("userFullName"));
    critname.add(Restrictions.eq("userName", strUserName));
    critname.add(Restrictions.eq("userPassword", password));
    critname.setProjection(pl);
    List objs = getHibernateTemplate().findByCriteria(critname);
    if ((objs != null) && (objs.size() > 0)) {
        obj = (String) objs.get(0);
    }
    return obj;
}