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.github.javarch.repository.HibernateBaseRepositoryIntegrationTest.java

License:Apache License

@Test
public void testLoadProjecao() {

    Projection p = Projections.projectionList().add(Projections.property("email"), "email");

    List<User> users = defaultRepository.findAll(User.class, p);
    assertNotNull(users);//from   www.  j a v a 2s  .  c  om

    for (User User : users) {
        assertNotNull(User.getEmail());
        assertNull(User.getNomeUsuario());
        assertNull(User.getSenha());
        assertTrue(User.getBlogs().isEmpty());
    }
}

From source file:com.gps.rptbean.DataSourceFactory.java

public static JRDataSource buildYearlyDataSource(Vehicle v, String year, String measureName) {

    assert (v != null);
    assert (year != null);

    Date startDate = null;/*from   w  w w.ja v  a  2  s. com*/
    try {
        startDate = (new SimpleDateFormat("yyyy")).parse(year);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Calendar cal = Calendar.getInstance();
    cal.setTime(startDate);
    cal.add(Calendar.YEAR, 1);
    Date endDate = cal.getTime();

    Session session = HibernateUtil.getSession();

    List results = session.createCriteria(FRuningLog.class)
            .setProjection(Projections.projectionList().add(Projections.rowCount(), "rowCount")
                    .add(Projections.sum(measureName), "total")
                    .add(Projections.groupProperty("yearMonth"), "yearMonth"))
            .add(Restrictions.eq("vehicle.vehicleId", v.getVehicleId()))
            .add(Restrictions.le("startDate", endDate)).add(Restrictions.ge("startDate", startDate))
            .addOrder(Order.asc("yearMonth")).list();

    //   
    //      FRuningLogBean fruningLogBean = new FRuningLogBean();
    //      
    //      fruningLogBean.setVehicleId(v.getVehicleId());
    //      fruningLogBean.setStartDateStart(startDate);
    //      fruningLogBean.setStartDateEnd(endDate);
    //      
    //      fruningLogBean.getList();
    YearlyDataSource ds = null;
    ds = new YearlyDataSource();

    Iterator iter = results.iterator();

    while (iter.hasNext()) {
        Object[] row = (Object[]) iter.next();
        Integer count = (Integer) row[0];
        Double total = (Double) row[1];
        String yearMonth = (String) row[2];

        int idx = getIndex(yearMonth);
        YearlyBean bean = new YearlyBean(idx);
        bean.setVehicleId(v.getVehicleId());
        bean.setLicensePad(v.getLicensPadNumber());
        bean.setMeasure1(total);
        ds.addRecord(idx, bean);
    }

    return ds;

}

From source file:com.gps.rptbean.DataSourceFactory.java

public static JRDataSource buildMonthlyCostDataSource(Vehicle v, Date start, Date end) {

    CostAnalysisDataSource result = new CostAnalysisDataSource();

    assert (v != null);
    assert (start != null);
    assert (end != null);
    int index = 1;

    Session session = HibernateUtil.getSession();

    List results = session.createCriteria(FRuningLog.class)
            .setProjection(Projections.projectionList().add(Projections.rowCount(), "runCount")
                    .add(Projections.sum("totalCost"), "total").add(Projections.sum("actualGas"), "totalGas")
                    .add(Projections.sum("gasByCashCost"), "totalGasCash")
                    .add(Projections.sum("gasByCardCost"), "totalGasCard")
                    .add(Projections.sum("actualDistance"), "totalDistance")
                    .add(Projections.sum("actualRoadFee"), "totalRoadFee")
                    .add(Projections.sum("overLimitFee"), "totalOverLimitFee")
                    .add(Projections.groupProperty("vehicle.vehicleId"), "vehicleId"))
            .add(Restrictions.eq("vehicle.vehicleId", v.getVehicleId())).add(Restrictions.le("startDate", end))
            .add(Restrictions.ge("startDate", start)).list();

    Double gas = (Double) ((Object[]) results.get(0))[2];
    Double gasByCash = (Double) ((Object[]) results.get(0))[3];
    Double gasByCard = (Double) ((Object[]) results.get(0))[4];

    Double gasFee = gasByCash + gasByCard;
    Double roadFee = (Double) ((Object[]) results.get(0))[6];
    Double limitFee = (Double) ((Object[]) results.get(0))[7];

    CostAnalysisBean bean1 = new CostAnalysisBean();
    bean1.setCategoryName("");
    bean1.setIndex(index);/* ww  w .  j a v a2s.  c  om*/
    bean1.setLicensePad(v.getLicensPadNumber());
    bean1.setMeasure1(gasFee);
    bean1.setVehicleId(v.getVehicleId());
    result.addRecord(index - 1, bean1);
    index++;

    CostAnalysisBean bean2 = new CostAnalysisBean();
    bean2.setCategoryName("");
    bean2.setIndex(index);
    bean2.setLicensePad(v.getLicensPadNumber());
    bean2.setMeasure1(roadFee);
    bean2.setVehicleId(v.getVehicleId());
    result.addRecord(index - 1, bean2);
    index++;

    CostAnalysisBean bean3 = new CostAnalysisBean();
    bean3.setCategoryName("?");
    bean3.setIndex(index);
    bean3.setLicensePad(v.getLicensPadNumber());
    bean3.setMeasure1(limitFee);
    bean3.setVehicleId(v.getVehicleId());
    result.addRecord(index - 1, bean3);
    index++;

    results = null;
    results = session.createCriteria(FMaintain.class)
            .setProjection(Projections.projectionList().add(Projections.rowCount(), "runCount")
                    .add(Projections.sum("cost"), "total")
                    .add(Projections.groupProperty("vehicle.vehicleId"), "vehicleId"))
            .add(Restrictions.eq("vehicle.vehicleId", v.getVehicleId()))
            .add(Restrictions.le("maintainDate", end)).add(Restrictions.ge("maintainDate", start)).list();

    if (results.size() > 0) {
        Double maitainFee = (Double) ((Object[]) results.get(0))[1];

        CostAnalysisBean bean4 = new CostAnalysisBean();
        bean4.setCategoryName("?");
        bean4.setIndex(index);
        bean4.setLicensePad(v.getLicensPadNumber());
        bean4.setMeasure1(maitainFee);
        bean4.setVehicleId(v.getVehicleId());
        result.addRecord(index - 1, bean4);
        index++;
    }

    String yearMonth = new SimpleDateFormat("yyyyMM").format(start);
    results = null;
    results = session.createCriteria(FExpenseLog.class)
            .setProjection(Projections.projectionList().add(Projections.rowCount(), "runCount")
                    .add(Projections.sum("amount"), "total")
                    .add(Projections.groupProperty("category1"), "category1"))
            .add(Restrictions.eq("vehicle.vehicleId", v.getVehicleId()))
            .add(Restrictions.eq("yearMonth", yearMonth)).list();

    Iterator iter = results.iterator();

    while (iter.hasNext()) {
        Object[] row = (Object[]) iter.next();
        Integer count = (Integer) row[0];
        Double total = (Double) row[1];
        String category = (String) row[2];

        CostAnalysisBean bean = new CostAnalysisBean();
        bean.setIndex(index);
        bean.setCategoryName(category);
        bean.setVehicleId(v.getVehicleId());
        bean.setLicensePad(v.getLicensPadNumber());
        bean.setMeasure1(total);
        result.addRecord(index - 1, bean);
        index++;
    }

    return result;
}

From source file:com.griffinslogistics.book.BookService.java

@Override
public List<BookModel> getBookModelsByTransportId(Long transportId) {
    logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation started", CLASS_NAME);

    List<BookModel> resultList = new ArrayList<BookModel>();

    try {/*from  w  w w  . j a  v a2 s . c o  m*/
        DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);
        criteria.add(Restrictions.eq("transportId", transportId));
        criteria.setProjection(
                Projections.projectionList().add(Projections.groupProperty("bookNumber"), "bookNumber")
                        .add(Projections.property("title"), "title"))
                .setResultTransformer(Transformers.aliasToBean(BookModel.class));

        resultList = (List<BookModel>) this.dao.getAllByDetachedCriteria(criteria);
        Collections.reverse(resultList);

    } catch (HibernateException e) {

        logger.log(Level.SEVERE, e.getMessage());
    } finally {

        logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation finished", CLASS_NAME);
    }

    return resultList;
}

From source file:com.griffinslogistics.db.helpers.BooksHelper.java

public List<BookModel> getBookModelsByTransportation(Transportation transportation) {
    logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation started", CLASS_NAME);

    List<BookModel> resultList = new ArrayList<BookModel>();

    this.session = HibernateUtil.getSessionFactory().openSession();
    Transaction transaction = this.session.beginTransaction();

    try {/*from w  w  w .j ava2  s .  c om*/
        Criteria criteria = this.session.createCriteria(Book.class);
        criteria.add(Restrictions.eq("transportation", transportation));
        criteria.setProjection(
                Projections.projectionList().add(Projections.groupProperty("bookNumber"), "bookNumber")
                        .add(Projections.property("title"), "title"))
                .setResultTransformer(Transformers.aliasToBean(BookModel.class));

        resultList = criteria.list();
        Collections.reverse(resultList);
        transaction.commit();
    } catch (HibernateException e) {
        transaction.rollback();
        logger.log(Level.SEVERE, e.getMessage());
    } finally {
        this.session.close();

        logger.log(Level.SEVERE, "{0}: getBookModelsByTransportation finished", CLASS_NAME);
    }

    return resultList;
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Adds a new projection list//from ww  w . j  a  va2s.com
 * @param attrs The attributes of the processed node.
 */
protected void startProjection(Attributes attrs) {
    projectionsName = attrs.getValue("name");
    projectionStack.push(Projections.projectionList());
}

From source file:com.heliosapm.aa4h.parser.XMLQueryParser.java

License:Apache License

/**
 * Initializes a Criteria Query./* w  w w .  ja  v a 2  s .c  o  m*/
 * Mandatory Attributes:<ul>
 * <li><b>name</b>: The unqualified class name driving the criteria query.</li>
 * </ul>
 * Optional Attributes:<ul>
 * <li><b>prefix</b>: The package name of the class driving the criteria query. If null, no package is assumed.</li>
 * <li><b>maxSize</b>: The maximum number of rows to return from the database.</li>
 * <li><b>fetchSize</b>: The number of rows to fetch when rows are requested. Usually not useful for AA4H.</li>
 * <li><b>cacheEnabled</b>: Enables or disables caching for the queried objects.</li>
 * <li><b>cacheMode</b>: The cache options for the queried objects.</li>
 * <li><b>flushMode</b>: The session flush options.</li>
 * <li><b>fetchMode</b>: The collection fetch options for the query.</li>
 * <li><b>lockMode</b>: The row lock options for the queried rows.</li>
 * <li><b>timeOut</b>: The query timeout option.</li>
 * <li><b>rowCountOnly</b>: Returns a count of the query rows only.</li>
 * </ul>
 * @param attrs The attributes of the processed node.
 * @return An appended or new CriteriaSpecification
 * @throws SAXException
 */
protected CriteriaSpecification processCriteria(Attributes attrs) throws SAXException {
    if (inDetached) {
        return criteriaStack.peek();
    }
    String name = attrs.getValue("name");
    String prefix = attrs.getValue("prefix");
    if (prefix != null) {
        className = prefix + "." + name;
    } else {
        className = name;
    }
    String maxSize = attrs.getValue("maxSize");
    String fetchSize = attrs.getValue("fetchSize");
    String firstResult = attrs.getValue("firstResult");
    String cacheEnabled = attrs.getValue("cacheEnabled");
    String cacheMode = attrs.getValue("cacheMode");
    String flushMode = attrs.getValue("flushMode");
    String fetchMode = attrs.getValue("fetchMode");
    String lockMode = attrs.getValue("lockMode");
    String timeOut = attrs.getValue("timeOut");
    String rowCountOnly = attrs.getValue("rowCountOnly");
    Criteria newCriteria = null;
    try {
        if (criteriaStack.size() == 0) {
            newCriteria = session.createCriteria(className);
        } else {
            newCriteria = ((Criteria) criteriaStack.peek()).createCriteria(className);
        }
        criteriaStack.push(newCriteria);
        if ("true".equalsIgnoreCase(rowCountOnly)) {
            newCriteria.setProjection(Projections.projectionList().add(Projections.rowCount())

            );
            setRowCountOnly(true);
        }
        if (maxSize != null && isRowCountOnly() == false) {
            newCriteria.setMaxResults(Integer.parseInt(maxSize));
        }
        if (fetchSize != null && isRowCountOnly() == false) {
            newCriteria.setFetchSize(Integer.parseInt(fetchSize));
        }
        if (firstResult != null && isRowCountOnly() == false) {
            newCriteria.setFirstResult(Integer.parseInt(firstResult));
        }
        if (timeOut != null) {
            newCriteria.setTimeout(Integer.parseInt(timeOut));
        }

        if ("true".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(true);
        } else if ("false".equalsIgnoreCase(cacheEnabled)) {
            newCriteria.setCacheable(false);
        }
        if (fetchMode != null && fetchMode.length() > 0) {
            if ("JOIN".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.JOIN);
            } else if ("SELECT".equalsIgnoreCase(fetchMode)) {
                newCriteria.setFetchMode(name, FetchMode.SELECT);
            } else {
                newCriteria.setFetchMode(name, FetchMode.DEFAULT);
            }
        } else {
            newCriteria.setFetchMode(name, FetchMode.DEFAULT);
        }
        if (cacheMode != null && cacheMode.length() > 0) {
            if ("GET".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.GET);
            } else if ("IGNORE".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.IGNORE);
            } else if ("NORMAL".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            } else if ("PUT".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.PUT);
            } else if ("REFRESH".equalsIgnoreCase(cacheMode)) {
                newCriteria.setCacheMode(CacheMode.REFRESH);
            } else {
                newCriteria.setCacheMode(CacheMode.NORMAL);
            }
        }
        if (lockMode != null && lockMode.length() > 0) {
            if ("NONE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.NONE);
            } else if ("READ".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.READ);
            } else if ("UPGRADE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE);
            } else if ("UPGRADE_NOWAIT".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.UPGRADE_NOWAIT);
            } else if ("WRITE".equalsIgnoreCase(lockMode)) {
                newCriteria.setLockMode(LockMode.WRITE);
            } else {
                throw new SAXException("lockMode[" + lockMode + "] Not Recognized");
            }
        }
        if (flushMode != null && flushMode.length() > 0) {
            if ("ALWAYS".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.ALWAYS);
            } else if ("AUTO".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.AUTO);
            } else if ("COMMIT".equalsIgnoreCase(flushMode)) {
                newCriteria.setFlushMode(FlushMode.COMMIT);
            } else if ("NEVER".equalsIgnoreCase(flushMode)) {
                // NEVER is deprecated, so we won't throw an exception but we'll ignore it.
            } else {
                throw new SAXException("flushMode[" + flushMode + "] Not Recognized");
            }
        }
        return newCriteria;

    } catch (Exception e) {
        throw new SAXException("Unable to configure class " + className, e);
    }
}

From source file:com.hibernate.dao.AsesinosDAO.java

@Override
public List<Asesinos> getAsesinosListByProjection() {

    List<Asesinos> peliculas1 = session.createCriteria(Asesinos.class)//.list();
            .setProjection(Projections.projectionList().add(Projections.rowCount())
                    .add(Projections.avg("personasasesinadas")).add(Projections.max("personasasesinadas"))
                    .add(Projections.groupProperty("formato").as("ao"))

            ).list();/*from   ww  w .  j  a v a 2  s . c o m*/

    return peliculas1;
}

From source file:com.hrms.manager.GasManager.java

public List consumerno(Gasdto q) {
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
    List<GasConnectionMaster> list1 = null;
    int empId = q.getEmpId();
    String quartertype = null;// ww  w  . j  a va 2 s.com
    String sql = null;
    List quartercode;
    // List l=null;
    List<GasAllotment> list = (List<GasAllotment>) session.createCriteria(GasAllotment.class).list();
    if (list.isEmpty()) {
        Criteria cr = session.createCriteria(GasConnectionMaster.class).setProjection(
                Projections.projectionList().add(Projections.property("consumerNumber"), "consumerNumber"));

        list1 = cr.list();
        System.out.println(list1);
        return list1;
    } else

        sql = "select r.consumer_number from gas_connection_master r where  r.connection_id not in (select connection_id from gas_allotment) ";
    SQLQuery query = session.createSQLQuery(sql);
    //  query.setParameter("quartertype",quartertype);
    quartercode = query.list();

    //     System.out.println(quartercode);
    return quartercode;
}

From source file:com.hypersocket.repository.AbstractRepositoryImpl.java

License:Open Source License

@Override
public List<?> getCounts(Class<?> clz, String groupBy, CriteriaConfiguration... configs) {

    Criteria criteria = createCriteria(clz);

    for (CriteriaConfiguration c : configs) {
        c.configure(criteria);//from  ww  w . ja va  2 s  . c  o  m
    }

    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    criteria.setProjection(Projections.projectionList().add(Projections.groupProperty(groupBy))
            .add(Projections.count(groupBy)));

    return criteria.list();
}