Example usage for org.hibernate FetchMode EAGER

List of usage examples for org.hibernate FetchMode EAGER

Introduction

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

Prototype

FetchMode EAGER

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

Click Source Link

Document

Fetch eagerly, using an outer join.

Usage

From source file:br.com.nfsconsultoria.nfsuporte.dao.GenericDAO.java

public List<Entidade> listarLazy(String objeto) {
    Session sessao = HibernateUtil.getFabricaDeSessoes().openSession();

    try {/* w w w  .  j a v  a 2 s  .c  o m*/
        Criteria consulta = sessao.createCriteria(classe).setFetchMode(objeto, FetchMode.EAGER);
        List<Entidade> resultado = consulta.list();
        return resultado;
    } catch (RuntimeException erro) {
        throw erro;
    } finally {
        sessao.close();
    }
}

From source file:co.com.codesoftware.logica.facturacion.FacturaCompraTmpLogica.java

/**
 * metodo que consulta la factura temporal de compra por id
 *
 * @param idFactura//  w w w.  jav a 2s .  c o  m
 * @return
 */
public FacturaCompraTmpEntity consultaFacturaTemporal(Integer idFactura) {
    FacturaCompraTmpEntity respuesta = new FacturaCompraTmpEntity();
    try {
        initOperation();
        Criteria crit = this.sesion.createCriteria(FacturaCompraTmpEntity.class);
        crit.setFetchMode("proveedor", FetchMode.EAGER);
        crit.setFetchMode("sede", FetchMode.JOIN);
        crit.setFetchMode("proveedor.retenciones", FetchMode.JOIN);
        crit.setFetchMode("proveedor.municipio", FetchMode.JOIN);
        crit.setFetchMode("proveedor.ciudad", FetchMode.JOIN);
        respuesta = (FacturaCompraTmpEntity) crit.add(Restrictions.eq("id", idFactura)).uniqueResult();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return respuesta;
}

From source file:com.abssh.util.GenericDao.java

License:Apache License

private Object _get(final List<PropertyFilter> filters, Class clazz, final String... lazyObjects) {
    Criteria criteria = getSession().createCriteria(clazz);
    Map<String, Criteria> criteriaMap = new HashMap<String, Criteria>();
    for (PropertyFilter filter : filters) {
        if (!filter.isMultiProperty()) {
            String propertyName = filter.getPropertyName();
            Object[] propertyValue = filter.getPropertyValue();
            MatchType matchType = filter.getMatchType();
            Criteria parent = findParentCriteria(criteria, propertyName, criteriaMap);
            String[] tmp = StringUtils.split(propertyName, DEF_SEPARATOR);
            parent.add(getCriterion(tmp[tmp.length - 1], propertyValue, matchType));
        } else {/*from  www  .j a v a  2  s  . c  om*/
            Disjunction disjunction = Restrictions.disjunction();
            Object[] propertyValue = filter.getPropertyValue();
            MatchType matchType = filter.getMatchType();
            for (String propertyName : filter.getPropertyNames()) {
                Criteria parent = findParentCriteria(criteria, propertyName, criteriaMap);
                String[] tmp = StringUtils.split(propertyName, DEF_SEPARATOR);
                parent.add(getCriterion(tmp[tmp.length - 1], propertyValue, matchType));
            }
            criteria.add(disjunction);
        }
    }
    // criteria.setMaxResults(1);

    if (lazyObjects != null) {
        for (int i = 0; i < lazyObjects.length; i++) {
            criteria.setFetchMode(lazyObjects[i], FetchMode.EAGER);
        }
    }

    List result = criteria.list();
    if (result == null || result.size() == 0) {
        return null;
    } else {
        return result.get(0);
    }
}

From source file:com.abssh.util.GenericDao.java

License:Apache License

@SuppressWarnings("unchecked")
public Page<T> findPageDynamicFetch(final Page<T> page, final List<PropertyFilter> filters,
        final String... lazyObjects) {
    Criteria criteria = getSession().createCriteria(entityClass);
    Map<String, Criteria> criteriaMap = new HashMap<String, Criteria>();
    for (PropertyFilter filter : filters) {
        if (!MatchType.INS.equals(filter.getMatchType())) {
            if (!filter.isMultiProperty()) {
                String propertyName = filter.getPropertyName();
                Object[] propertyValue = filter.getPropertyValue();
                MatchType matchType = filter.getMatchType();
                Criteria parent = findParentCriteria(criteria, propertyName, criteriaMap);
                String[] tmp = StringUtils.split(propertyName, DEF_SEPARATOR);
                parent.add(getCriterion(tmp[tmp.length - 1], propertyValue, matchType));
            } else {
                Disjunction disjunction = Restrictions.disjunction();
                Object[] propertyValue = filter.getPropertyValue();
                MatchType matchType = filter.getMatchType();
                String[] propertyNames = filter.getPropertyNames();
                for (String propertyName : propertyNames) {
                    // Criteria parent = findParentCriteria(criteria,
                    // propertyName, criteriaMap);
                    String[] tmp = StringUtils.split(propertyName, DEF_SEPARATOR);
                    // parent.add(getCriterion(tmp[tmp.length - 1],
                    // propertyValue, matchType));
                    for (int i = 0; i <= tmp.length - 2; i++) {
                        criteria.createAlias(tmp[i], tmp[i], CriteriaSpecification.LEFT_JOIN);
                    }//from   ww w. jav a2  s .  c  om
                    // disjunction.ad
                }
                criteria.add(Restrictions.or(
                        Restrictions.like(propertyNames[0], propertyValue[0].toString(), MatchMode.ANYWHERE),
                        Restrictions.like(propertyNames[1], propertyValue[0].toString(), MatchMode.ANYWHERE)));

                // criteria.add(disjunction);
            }
        } else {
            criteria.add(org.hibernate.criterion.Expression.sql("this_." + filter.getPropertyName() + " in "
                    + String.valueOf(filter.getPropertyValue()[0])));
        }
    }
    if (lazyObjects != null) {
        for (int i = 0; i < lazyObjects.length; i++) {
            criteria.setFetchMode(lazyObjects[i], FetchMode.EAGER);
        }
    }
    if (page != null && page.isAutoCount()) {
        int totalCount = countCriteriaResult(criteria);
        page.setTotalCount(totalCount);
    }
    if (page != null && page.getPageSize() > 0) {
        if (page.getTotalPages() < page.getPageNo()) {
            page.setPageNo(1L);
        }
        criteria.setFirstResult(page.getFirst() - 1);
        criteria.setMaxResults(page.getPageSize());
    }
    if (page != null && page.isOrderBySetted()) {
        String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
        String[] orderArray = StringUtils.split(page.getOrder(), ',');

        Assert.isTrue(orderByArray.length == orderArray.length, "orderBy and order is not suited!");

        for (int i = 0; i < orderByArray.length; i++) {
            if (orderByArray[i].indexOf(".") > 0) {
                // ???
                if (Page.ASC.equals(orderArray[i])) {
                    Criteria p = criteriaMap
                            .get(orderByArray[i].substring(0, orderByArray[i].lastIndexOf(".")));
                    if (p == null) {
                        p = findParentCriteria(criteria, orderByArray[i], criteriaMap);// ??
                    }
                    p.addOrder(Order.asc(orderByArray[i].substring(orderByArray[i].lastIndexOf(".") + 1)));
                } else {
                    Criteria p = criteriaMap
                            .get(orderByArray[i].substring(0, orderByArray[i].lastIndexOf(".")));
                    if (p == null) {
                        p = findParentCriteria(criteria, orderByArray[i], criteriaMap);// ??
                    }
                    p.addOrder(Order.desc(orderByArray[i].substring(orderByArray[i].lastIndexOf(".") + 1)));
                }
            } else {
                if (Page.ASC.equals(orderArray[i])) {
                    criteria.addOrder(Order.asc(orderByArray[i]));
                } else {
                    criteria.addOrder(Order.desc(orderByArray[i]));
                }
            }
        }
    }

    List result = criteria.list();
    if (page == null) {
        Page p = new Page<T>();
        p.setResult(result);
        p.setTotalCount(result.size());
        p.setPageNo(1L);
        p.setPageSize(result.size());
        return p;
    }
    page.setResult(result);
    return page;
}

From source file:com.arg.arsoft.siantluis.repository.imp.ProductRepository.java

@Override
public Map findByQuery(ProductQuery query) {
    int pageSize = Configs.PAGE_SIZE;
    Criteria criteria = factory.getCurrentSession().createCriteria(Product.class);
    if (query.getCode() != null && !query.getCode().equals("")) {
        if (query.getCode().contains("*") || query.getCode().contains("?")) {
            criteria.add(org.hibernate.criterion.Restrictions.like("code",
                    query.getCode().replace("*", "%").replace("?", "_")));

        } else {/*from   w ww  .j  av a  2s .com*/
            criteria.add(org.hibernate.criterion.Restrictions.eq("code", query.getCode()));
        }
    }
    if (query.getName() != null && !query.getName().equals("")) {
        if (query.getName().contains("*") || query.getName().contains("?")) {
            criteria.add(org.hibernate.criterion.Restrictions.like("name",
                    query.getName().replace("*", "%").replace("?", "_")));
        } else {
            criteria.add(org.hibernate.criterion.Restrictions.eq("name", query.getName()));
        }
    }
    if (query.getSupplier() != null && !query.getSupplier().equals("")) {
        criteria.createAlias("supplier", "s", JoinType.LEFT_OUTER_JOIN);
        criteria.add(org.hibernate.criterion.Restrictions.eq("s.code", query.getSupplier()));
    }
    if (query.getActive() != null && !query.getActive().equals("")) {
        ProductActive active = ProductActive.valueOf(query.getActive());
        criteria.add(org.hibernate.criterion.Restrictions.eq("active", active));
    }
    long totalRecord = (long) criteria.setProjection(Projections.count(Projections.id().toString()))
            .uniqueResult();
    int start = ((query.getPage() - 1) * pageSize);

    criteria.setProjection(null);
    criteria.setFetchMode("supplier", FetchMode.EAGER);
    List<Product> result = criteria.setFirstResult(start).setMaxResults(pageSize)
            .setResultTransformer(Criteria.ROOT_ENTITY).list();

    long totalPage = totalRecord / pageSize;
    if ((totalRecord % pageSize) > 0) {
        totalPage++;
    }
    List<Integer> pages = new ArrayList<Integer>();
    for (int index = 1; index <= totalPage; index++) {
        pages.add(index);
    }
    Map data = new HashMap();
    data.put("list", result);
    data.put("totalPage", totalPage);
    data.put("totalRecord", totalRecord);
    data.put("pages", pages);

    return data;
}

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)
 *///from   w ww .  j a v a2 s  .  c o  m
@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.smartitengineering.dao.impl.hibernate.AbstractDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
private void processNestedParameter(Criteria criteria, String element, QueryParameter parameter) {
    FetchMode mode;//from  w w w. j  av a2  s  .  c om
    CompositionQueryParameter queryParameter = QueryParameterCastHelper.COMPOSITION_PARAM_FOR_NESTED_TYPE
            .cast(parameter);
    switch (queryParameter.getFetchMode()) {
    case EAGER:
        mode = FetchMode.EAGER;
        break;
    case SELECT:
        mode = FetchMode.SELECT;
        break;
    case JOIN:
        mode = FetchMode.JOIN;
        break;
    case LAZY:
        mode = FetchMode.LAZY;
        break;
    default:
    case DEFAULT:
        mode = FetchMode.DEFAULT;
        break;
    }
    criteria.setFetchMode(element, ((mode == null) ? FetchMode.JOIN : mode));
    Collection<QueryParameter> nestedParameters = queryParameter.getNestedParameters();
    if (nestedParameters == null || nestedParameters.size() <= 0) {
        return;
    }
    Criteria nestedCriteria = criteria.createCriteria(element);
    for (QueryParameter nestedQueryParameter : nestedParameters) {
        if (!nestedQueryParameter.isInitialized()) {
            continue;
        }
        processCriteria(nestedCriteria, getPropertyName(nestedQueryParameter), nestedQueryParameter);
    }
}

From source file:gov.nih.nci.caintegrator.studyQueryService.germline.GenotypeFindingsHandler.java

License:BSD License

protected void initializeProxies(Collection<? extends Finding> findings, Session session) {

    /* 1. initialize SNPAnnotations */
    Collection<Long> snpAnnotsIDs = new HashSet<Long>();
    for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
        GenotypeFinding finding = (GenotypeFinding) iterator.next();
        snpAnnotsIDs.add(finding.getSnpAnnotation().getId());
    }//from  w  w w .j a  v  a 2 s . c o  m
    if (snpAnnotsIDs.size() > 0) {
        ArrayList arrayIDs = new ArrayList(snpAnnotsIDs);
        for (int i = 0; i < arrayIDs.size();) {
            Collection values = new ArrayList();
            int begIndex = i;
            i += BatchFindingsHandler.IN_PARAMETERS;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex, lastIndex));
            Criteria crit = session.createCriteria(SNPAnnotation.class).add(Restrictions.in("id", values));
            crit.list();
        }
    }

    /* 2. initialize Specimens along with associated StudyParticipants */
    Collection<String> specimenIDs = new HashSet<String>();
    for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
        GenotypeFinding finding = (GenotypeFinding) iterator.next();
        specimenIDs.add(finding.getSpecimen().getSpecimenIdentifier());
    }

    if (specimenIDs.size() > 0) {
        ArrayList arrayIDs = new ArrayList(specimenIDs);
        for (int i = 0; i < arrayIDs.size();) {
            Collection values = new ArrayList();
            int begIndex = i;
            i += BatchFindingsHandler.IN_PARAMETERS;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex, lastIndex));
            Criteria specimenCrit = session.createCriteria(Specimen.class)
                    .add(Restrictions.in("specimenIdentifier", values))
                    .setFetchMode("studyParticipant", FetchMode.EAGER);

            specimenCrit.list();
        }
    }
}

From source file:gov.nih.nci.caintegrator.studyQueryService.germline.SNPFrequencyFindingHandler.java

License:BSD License

protected void initializeProxies(Collection<? extends Finding> findings, Session session) {

    /* initialize SNPAnnotations */
    Collection<Long> snpAnnotsIDs = new HashSet<Long>();
    Collection<Long> populationIDs = new HashSet<Long>();
    for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
        SNPFrequencyFinding finding = (SNPFrequencyFinding) iterator.next();
        snpAnnotsIDs.add(finding.getSnpAnnotation().getId());
        populationIDs.add(finding.getPopulation().getId());
    }/* ww  w  .  j  a va2s. c o m*/
    if (snpAnnotsIDs.size() > 0) {
        ArrayList arrayIDs = new ArrayList(snpAnnotsIDs);
        for (int i = 0; i < arrayIDs.size();) {
            Collection values = new ArrayList();
            int begIndex = i;
            i += IN_PARAMETERS;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex, lastIndex));
            Criteria snpAnnotcrit = session.createCriteria(SNPAnnotation.class)
                    .setFetchMode("geneBiomarkerCollection", FetchMode.EAGER)
                    .add(Restrictions.in("id", values));
            snpAnnotcrit.list();
        }
    }

    /* initialize Population */
    if (populationIDs.size() > 0) {
        Criteria populationCrit = session.createCriteria(Population.class)
                .add(Restrictions.in("id", populationIDs));
        populationCrit.list();
    }

    Collection findingIDs = new HashSet();
    for (Iterator<? extends Finding> iterator = findings.iterator(); iterator.hasNext();) {
        SNPFrequencyFinding finding = (SNPFrequencyFinding) iterator.next();
        findingIDs.add(finding.getId());
    }

    /*
            Criteria crit;
            ArrayList<String> arrayIDs = new ArrayList<String>(findingIDs);
            for (int i = 0; i < arrayIDs.size();) {
    List<String> values = new ArrayList<String>();
    int begIndex = i;
    i += 1000 ;
    int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
    values.addAll(arrayIDs.subList(begIndex,  lastIndex));
    crit = session.createCriteria(SNPAnnotation.class).
                              createAlias("snpFrequencyCollection", "findings").
                              setFetchMode("geneBiomarkerCollection", FetchMode.EAGER).
                              add(Restrictions.in("findings.id", values));
    crit.list();
            }
            
            for (int i = 0; i < arrayIDs.size();) {
    List<String> values = new ArrayList<String>();
    int begIndex = i;
    i += 1000 ;
    int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
    values.addAll(arrayIDs.subList(begIndex,  lastIndex));
    crit = session.createCriteria(Population.class).
                                createAlias("snpFrequencyCollection", "findings").
                                add(Restrictions.in("findings.id", values));
    crit.list();
            }
    */
}

From source file:gov.nih.nci.caintegrator.studyQueryService.germline.SubjectSearchHandler.java

License:BSD License

public Collection<StudyParticipant> getStudySubjects(StudyParticipantCriteria spCrit, int fromIndex,
        int toIndex) {
    Session session = getSessionFactory().getCurrentSession();
    List<Long> specimenIDs = StudyParticipantCriteriaHandler.retrieveSpecimens(spCrit, session);
    List<StudyParticipant> subjects = new ArrayList<StudyParticipant>();
    HashSet<StudyParticipant> subjectsSet = new HashSet<StudyParticipant>();
    Criteria crit = null;//  ww w . j a  v a  2 s.  co m

    if (specimenIDs == null) {
        /* meanse either StudyParticipantCriteria  is null or no StudyParticipantCriteria
         attributes are mentioned.  So ignore StudyParticipantCriteria and return all StudyParticipant* */
        crit = session.createCriteria(StudyParticipant.class).setFetchMode("populationCollection",
                FetchMode.EAGER);
        //crit.setFirstResult(fromIndex);
        //crit.setMaxResults(toIndex - fromIndex);
        List<StudyParticipant> list = crit.list();
        subjectsSet.addAll(list);
        subjects.addAll(subjectsSet);
    } else if (specimenIDs.size() == 0) {
        /* means StudyParticipantCriteria did not select and Specimens  Hence return
           no StudyParticipants */
        return subjects;
    }
    /*  means  specimens.size() > 0 so retrieve StudyPartipants beased on the Specimens */
    else if (specimenIDs != null && specimenIDs.size() > 0) {
        ArrayList<Long> arrayIDs = new ArrayList<Long>(specimenIDs);
        for (int i = 0; i < arrayIDs.size();) {
            List<Long> values = new ArrayList<Long>();
            int begIndex = i;
            i += BatchFindingsHandler.IN_PARAMETERS;
            int lastIndex = (i < arrayIDs.size()) ? i : (arrayIDs.size());
            values.addAll(arrayIDs.subList(begIndex, lastIndex));
            crit = session.createCriteria(StudyParticipant.class).createAlias("specimenCollection", "specimens")
                    .setFetchMode("populationCollection", FetchMode.EAGER)
                    .add(Restrictions.in("specimens.id", values));
            //crit.uniqueResult();
            //crit.setFirstResult(0);
            //crit.setMaxResults(toIndex - fromIndex);
            Collection<StudyParticipant> studySubjects = crit.list();
            // avoid duplicates
            subjectsSet.addAll(studySubjects);
            if (subjects.size() >= (toIndex - fromIndex + 1)) {
                subjects.addAll(subjectsSet);
                subjectsSet = null;
                return subjects.subList(0, (toIndex - fromIndex));
            }
        }

        /* means each time it never gotten more than 500 results.  So add to final results */
        subjects.addAll(subjectsSet);
    }
    return subjects;
}