Example usage for org.hibernate FetchMode JOIN

List of usage examples for org.hibernate FetchMode JOIN

Introduction

In this page you can find the example usage for org.hibernate FetchMode JOIN.

Prototype

FetchMode JOIN

To view the source code for org.hibernate FetchMode JOIN.

Click Source Link

Document

Fetch using an outer join.

Usage

From source file:com.griffinslogistics.transport.TransportService.java

@Override
public Map<String, Double> totalWeightsForTransport(Long transportId) {

    Map<String, Double> result = new TreeMap<String, Double>();

    DetachedCriteria criteria = DetachedCriteria.forClass(Transport.class);
    criteria.add(Restrictions.eq("id", transportId));
    criteria.setFetchMode("bookspackages", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.truckGroup", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.books", FetchMode.JOIN);
    criteria.setFetchMode("bookspackages.books.boxes", FetchMode.JOIN);
    Transport transport = (Transport) this.transportDAO.getByDetachedCriteria(criteria);

    String transportationString = String.format("? %s/%s", transport.getWeekNumber(),
            transport.getYear());/* w  w  w . j  a  v  a2  s .  c o  m*/

    Set<Bookspackage> bookspackages = transport.getBookspackages();

    for (Bookspackage bookspackage : bookspackages) {

        double totalWeightForTruckGroup = 0;

        for (Book book : bookspackage.getBooks()) {
            double weightPerBook = book.getWeightPerBook();

            totalWeightForTruckGroup += book.getCount() * weightPerBook;
        }

        if (totalWeightForTruckGroup > 0) {
            double totalWeightForTransport = totalWeightForTruckGroup;

            if (result.containsKey(transportationString)) {
                totalWeightForTransport += result.get(transportationString);
            }

            result.put(transportationString, totalWeightForTransport);

            TruckGroup truckGroup = bookspackage.getTruckGroup();

            String keyName;

            if (truckGroup != null) {
                keyName = bookspackage.getTruckGroup().getName();
            } else {
                keyName = resourceBundleBean.get(ResourceBundleBean.NO_TRUCK_GROUP);
            }

            if (result.containsKey(keyName)) {
                totalWeightForTruckGroup += result.get(keyName);
            }

            result.put(keyName, totalWeightForTruckGroup);
        }
    }
    return result;
}

From source file:com.griffinslogistics.truckgroup.TruckGroupService.java

@Override
public Map<String, TruckGroupTotalsModel> getTruckGroupTotalsForTransport(Long transportId) {
    logger.log(Level.SEVERE, "{0}: getTruckGroupTotalsForTransport started", CLASS_NAME);

    Map<String, TruckGroupTotalsModel> resultModels = new HashMap<String, TruckGroupTotalsModel>();

    try {// w  w w  .  jav a  2 s  .  co  m
        DetachedCriteria criteria = DetachedCriteria.forClass(Transport.class);
        criteria.add(Restrictions.eq("id", transportId));
        criteria.setFetchMode("bookspackages", FetchMode.JOIN);
        criteria.setFetchMode("bookspackages.truckGroup", FetchMode.JOIN);
        criteria.setFetchMode("bookspackages.books", FetchMode.JOIN);
        criteria.setFetchMode("bookspackages.books.boxes", FetchMode.JOIN);
        Transport transport = (Transport) this.dao.getByDetachedCriteria(criteria);

        Set<Bookspackage> bookspackages = transport.getBookspackages();

        for (Bookspackage bookspackage : bookspackages) {

            double totalWeightForTruckGroup = 0;
            double totalOrderedBooksWeight = 0;

            for (Book book : bookspackage.getBooks()) {
                double weightPerBook = book.getWeightPerBook();

                totalOrderedBooksWeight += book.getWeight();

                for (Box box : (Set<Box>) book.getBoxes()) {
                    totalWeightForTruckGroup += box.getBooksCount() * box.getBoxesCount() * weightPerBook;
                }
            }

            if (totalWeightForTruckGroup > 0) {

                TruckGroup truckGroup = bookspackage.getTruckGroup();

                if (truckGroup != null) {

                    TruckGroupTotalsModel model;

                    if (resultModels.containsKey(truckGroup.getName())) {
                        model = resultModels.get(truckGroup.getName());
                    } else {
                        model = new TruckGroupTotalsModel(truckGroup.getId(), truckGroup.getName(), 0, 0, 0d);
                    }

                    model.setPackagesCount(model.getPackagesCount() + 1);
                    model.setArrivedWeight(model.getArrivedWeight() + (int) totalWeightForTruckGroup);
                    double newTotalPrice = model.getTotalPrice()
                            + (totalOrderedBooksWeight * bookspackage.getPricePerKilogram().doubleValue());
                    model.setTotalPrice(newTotalPrice);

                    resultModels.put(truckGroup.getName(), model);
                }
            }
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage());
    } finally {
        logger.log(Level.SEVERE, "{0}: getTruckGroupTotalsForTransport finished", CLASS_NAME);
    }

    return resultModels;
}

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

License:Apache License

/**
 * Initializes a Criteria Query./*w w w .j  a  va  2s . c  om*/
 * 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.hmsinc.epicenter.model.analysis.impl.MaterializedViewAnalysisQueries.java

License:Open Source License

@SuppressWarnings("unchecked")
public org.hibernate.Criteria createGetCasesQuery(AnalysisParameters analysisParameters, Long offset,
        Long numRows) {/*from  w ww .  j  av a  2s .  c o m*/

    Validate.notNull(offset, "Offset must be set.");
    Validate.notNull(numRows, "Number of returned rows must be set.");
    Validate.notNull(analysisParameters.getDataType(), "Data type must be set.");

    Class<? extends Interaction> interactionClass = null;
    for (ClassificationTarget target : analysisParameters.getDataType().getTargets()) {
        Validate.notNull(target.getInteractionClass(), "Interaction class was null for " + target.toString());
        if (interactionClass == null) {
            interactionClass = target.getInteractionClass();
        } else {
            Validate.isTrue(interactionClass.equals(target.getInteractionClass()),
                    "Inconsistent interaction classes");
        }
    }

    // Query is a subselect of Interaction based on materialized view.
    final Class<? extends Serializable> mv = (analysisParameters.getClassifications() == null
            || analysisParameters.getClassifications().size() == 0 ? AnalysisView.class
                    : ClassifiedAnalysisView.class);

    final QueryBuilder query = new QueryBuilder().addEntity(mv, "analysis").addProperty("distinct(analysis.id)")
            .addProperty("analysis.interactionDate").addOrder("analysis.interactionDate asc");

    applyAttributes(query, analysisParameters);
    applyClassifications(query, analysisParameters);

    // Geography
    applyGeography(query, analysisParameters.getContainer().getClass(), analysisParameters);

    disableNestedLoops(entityManager);

    final Query q = query.toQuery((Session) entityManager.getDelegate(), true);

    q.setFirstResult(offset.intValue());
    q.setMaxResults(numRows.intValue());
    final List<Object[]> items = q.list();
    final List<Long> interactionList = new ArrayList<Long>();
    for (Object[] item : items) {
        interactionList.add((Long) item[0]);
    }
    Criteria ret = null;

    enableNestedLoops(entityManager);

    if (interactionList.size() > 0) {

        // We need to use a ResultTransformer here to avoid duplicate rows.
        ret = criteriaQuery(entityManager, interactionClass).setFetchMode("classifications", FetchMode.JOIN)
                .setFetchMode("patient", FetchMode.JOIN).setFetchMode("patientDetail", FetchMode.JOIN)
                .add(Restrictions.in("id", interactionList))
                .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    }
    return ret;
}

From source file:com.ihsolution.hqipo.dao.utils.QueryHelper.java

License:Open Source License

/**
 * convert the InputDTO to QueryHelper to get the count (omitting sort order)
 *//*  w w  w . j  a v  a 2  s .  c  om*/
@SuppressWarnings("deprecation")
public QueryHelper convertDtoToQhelperForCount(InputDTO dto) {
    if (dto == null)
        return this;
    this.dto = dto;
    int ind = 0;
    try {
        Junction j = null;
        Junction conj = Restrictions.conjunction();
        Junction disj = Restrictions.disjunction();
        String operator = "";
        boolean disjB = false, conjB = false;
        if (dto.getFetchMode() != null) {
            for (Map.Entry<String, String> entry : dto.getFetchMode().entrySet()) {
                FetchMode fmode = null;
                logger.debug("FetchMode key=" + entry.getKey() + " val=" + entry.getValue());
                if (entry.getValue().equals("join"))
                    fmode = FetchMode.JOIN;
                else if (entry.getValue().equals("eager"))
                    fmode = FetchMode.EAGER;
                else if (entry.getValue().equals("lazy"))
                    fmode = FetchMode.LAZY;
                else
                    fmode = FetchMode.LAZY;
                this.detCriteria.setFetchMode(entry.getKey(), fmode);
            }
        }
        for (String field : dto.getFields()) {
            operator = dto.getOperators().get(ind);
            if ("or".equals(operator)) {
                j = disj;
                disjB = true;
            } else {
                j = conj;
                conjB = true;
            }
            this.addFieldAndVal(createAliases(field), dto.getValues().get(ind), dto.getOperations().get(ind),
                    j);
            ind++;
        }

        if (dto.getExpressions() != null) {
            for (String expr : dto.getExpressions()) {
                j.add(Expression.sql(expr));
            }
        }
        if (dto.getFieldsToSelect() != null && dto.getFieldsToSelect().length > 0) {
            ProjectionList prList = Projections.projectionList();
            Projection projection = null;

            for (String fld : dto.getFieldsToSelect()) {
                String als = this.createAliases(fld);
                prList.add(Projections.property(als));
            }
            if (dto.isDistinct()) {
                projection = Projections.distinct(prList);
            } else {
                projection = prList;
            }
            this.detCriteria.setProjection(projection);

        } else {
            this.fldSelectedSet = false;
        }

        if (disjB)
            detCriteria.add(disj);
        if (conjB)
            detCriteria.add(conj);
        if (logger.isDebugEnabled()) {
            if (conjB)
                logger.debug("conjuction=" + conj.toString());
            if (disjB)
                logger.debug("disjunction=" + disj.toString());
        }
        if (dto.isDistinct())
            detCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e);
    }
    return this;
}

From source file:com.indicator_engine.dao.GLACategoryDaoImpl.java

License:Open Source License

/**
 * Loads all the Category Items from Database..
 * @param colName Column Name to be used for sorting the results before it returns.
 * @param sortDirection Specifies the Sort Direction : asc or desc
 * @param sort Turn Sorting On or Off.//from   www .  j  ava  2  s .  c  o  m
 * @return Returns all the Category Items present in DB.
 */
@Override
@Transactional(readOnly = true)
public List<GLACategory> loadAll(String colName, String sortDirection, boolean sort) {
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLACategory.class);
    criteria.setFetchMode("events", FetchMode.JOIN);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (sort) {
        if (sortDirection.equals("asc"))
            criteria.addOrder(Order.asc(colName));
        else
            criteria.addOrder(Order.desc(colName));
    }
    return criteria.list();
}

From source file:com.indicator_engine.dao.GLACategoryDaoImpl.java

License:Open Source License

/**
 * Searches Category Items based on a Minor Value.
 * @param searchParameter Minor Value used for Searching.
 * @param exactSearch Search Type : Exact or Likewise.
 * @param colName Column Name used for Sorting the Results.
 * @param sortDirection Sorting Direction : Ascending/Descending.
 * @param sort Turn Sorting ON/OFF./*from  w ww  .ja  v a  2 s. com*/
 * @return Returns list of Matching GLACategory Items.
 */
@Override
@Transactional(readOnly = true)
public List<GLACategory> searchCategoryByMinor(String searchParameter, boolean exactSearch, String colName,
        String sortDirection, boolean sort) {
    if (!exactSearch)
        searchParameter = "%" + searchParameter + "%";
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLACategory.class);
    criteria.setFetchMode("events", FetchMode.JOIN);
    if (!exactSearch)
        criteria.add(Restrictions.ilike("minor", searchParameter));
    else
        criteria.add(Restrictions.eq("minor", searchParameter));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (sort) {
        if (sortDirection.equals("asc"))
            criteria.addOrder(Order.asc(colName));
        else
            criteria.addOrder(Order.desc(colName));
    }
    return criteria.list();
}

From source file:com.indicator_engine.dao.GLAEntityDaoImpl.java

License:Open Source License

/**
 * Loads all GLA Entity Objects present in the Database.
 * @param colName Sort the Results using this Column Name.
 * @param sortDirection Specify Sort Direction : asc/desc.
 * @param sort Turn Sorting ON/OFF//from  w  w w.j ava  2s .  c  o m
 * @return Returns all GLA Entity Objects present in Database and sorted if specified.
 **/
@Override
@Transactional(readOnly = true)
public List<GLAEntity> loadAll(String colName, String sortDirection, boolean sort) {
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLAEntity.class);
    criteria.createAlias("glaEvent", "events");
    criteria.setFetchMode("events", FetchMode.JOIN);
    criteria.createAlias("events.glaCategory", "category");
    criteria.setFetchMode("category", FetchMode.JOIN);
    criteria.createAlias("events.glaUser", "users");
    criteria.setFetchMode("users", FetchMode.JOIN);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    if (sort) {
        if (sortDirection.equals("asc"))
            criteria.addOrder(Order.asc(colName));
        else
            criteria.addOrder(Order.desc(colName));
    }
    return criteria.list();

}

From source file:com.indicator_engine.dao.GLAEntityDaoImpl.java

License:Open Source License

/**
 * Loads all GLA Entity Objects present in the Database based on a specific Category ID.
 * @param categoryID Category ID used for selecting relevant GLA Entity Objects.
 * @return Returns all GLA Entity Objects present in Database and matching the specified Category ID.
 **///from   w ww.  j  a va2  s .c  o m
@Override
@Transactional(readOnly = true)
public List<String> loadEntitiesByCategoryID(Long categoryID) {
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLAEntity.class);
    criteria.setProjection(Projections.distinct(Projections.property("key")));
    criteria.createAlias("glaEvent", "events");
    criteria.setFetchMode("events", FetchMode.JOIN);
    criteria.createAlias("events.glaCategory", "category");
    criteria.setFetchMode("category", FetchMode.JOIN);
    criteria.add(Restrictions.eq("category.id", categoryID));
    return criteria.list();

}

From source file:com.indicator_engine.dao.GLAEntityDaoImpl.java

License:Open Source License

/**
 * Loads all GLA Entity Keys present in the Database based on a specific Category ID.
 * @param categoryID Category ID used for selecting relevant GLA Entity Objects.
 * @return Returns all GLA Entity Keys present in Database and matching the specified Category ID.
 **//*from  w w w .  java  2s .  com*/
@Override
@Transactional(readOnly = true)
public List<String> loadEntityKeyValuesByCategoryID(Long categoryID, String key) {
    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(GLAEntity.class);
    criteria.createAlias("glaEvent", "events");
    criteria.setFetchMode("events", FetchMode.JOIN);
    criteria.createAlias("events.glaCategory", "category");
    criteria.setFetchMode("category", FetchMode.JOIN);
    criteria.add(Restrictions.eq("category.id", categoryID));
    criteria.add(Restrictions.eq("key", key));
    criteria.setProjection(Projections.property("value"));
    return criteria.list();

}