Example usage for org.hibernate Criteria setFetchMode

List of usage examples for org.hibernate Criteria setFetchMode

Introduction

In this page you can find the example usage for org.hibernate Criteria setFetchMode.

Prototype

public Criteria setFetchMode(String associationPath, FetchMode mode) throws HibernateException;

Source Link

Document

Specify an association fetching strategy for an association or a collection of values.

Usage

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  w  w  w .j a v a  2  s .c o m
            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.  j a  v a2 s  . c  o  m
                    // 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.abssh.util.GenericDao.java

License:Apache License

/**
 * /* w  w w . j  a  va2s . com*/
 * 
 * @date 2012-04-06
 * @param page
 * @param filters
 * @param criterions
 * @return
 */
@SuppressWarnings("unchecked")
public Page<T> findPage(final Page<T> page, final List<PropertyFilter> filters, String[] fetchObject,
        final Criterion... criterions) {
    Assert.notNull(page, "page should not be null!");

    Criterion[] cs = (Criterion[]) ArrayUtils.addAll(buildPropertyFilterCriterions(filters), criterions);
    Criteria c = createCriteria(cs);

    if (page.isAutoCount()) {
        int totalCount = countCriteriaResult(c);
        page.setTotalCount(totalCount);
    }
    if (page != null && page.getPageSize() > 0 && page.getTotalPages() < page.getPageNo()) {
        page.setPageNo(1L);
    }

    setPageParameter(c, page);
    if (fetchObject != null) {
        for (int i = 0; i < fetchObject.length; i++) {
            c.setFetchMode(fetchObject[i], FetchMode.JOIN);
        }
    }
    List<T> result = c.list();
    page.setResult(result);

    return page;
}

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

License:Apache License

public List<T> findDynamicFetch(final List<PropertyFilter> filters, String orderBy, String order,
        final String... lazyObjects) {
    Criteria criteria = getSession().createCriteria(entityClass);
    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 ww  w.  j av  a2 s  . com*/
            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);
        }
    }

    if (orderBy != null && !"".equals(orderBy)) {
        String[] orderByArray = StringUtils.split(orderBy, ',');
        String[] orderArray = StringUtils.split(order, ',');

        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]));
                }
            }
        }
    }

    if (lazyObjects != null) {
        for (int i = 0; i < lazyObjects.length; i++) {
            criteria.setFetchMode(lazyObjects[i], FetchMode.JOIN);
        }
    }
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    List result = criteria.list();

    return result;
}

From source file:com.algoTrader.CriteriaSearch.java

/**
 * Locates a <code>Criteria</code> for a <code>childEntityName</code>. If a
 * <code>Criteria</code> exists for the <code>childEntityName</code>, it is returned. If
 * not, one is created and referenced in the <code>childCriteriaMap</code> under the
 * <code>childEntityName</code>.
 *
 * @param childEntityName/*w  w  w . j a  v  a 2 s . c  om*/
 * @param parentCriteria
 * @return criteria The Criteria for the childEntityName.
 * @throws HibernateException
 */
private Criteria locateCriteria(String childEntityName, Criteria parentCriteria) throws HibernateException {
    if (this.childCriteriaMap.containsKey(childEntityName)) {
        return (Criteria) this.childCriteriaMap.get(childEntityName);
    }
    Criteria childCriteria = parentCriteria.createCriteria(childEntityName);
    if (this.configuration.isForceEagerLoading()) {
        parentCriteria.setFetchMode(childEntityName, FetchMode.JOIN);
    }

    // Hibernate does not support a 'unique' identifier. As a search may contain outer joins,
    // duplicates in the resultList are possible. We eliminate any duplicates here, creating a
    // distinctified resultSet (Suggestion from Hibernate itself; see www.hibernate.org's FAQ's).
    parentCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    this.childCriteriaMap.put(childEntityName, childCriteria);
    return childCriteria;
}

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

@Override
public Attachment findByKey(Integer key) {
    Criteria criteria = factory.getCurrentSession().createCriteria(Attachment.class);
    criteria.add(Restrictions.eq("id", key));
    // Fetch Relation
    criteria.setFetchMode("attachBy", FetchMode.JOIN);

    //Fetch Collection
    criteria.setFetchMode("items", FetchMode.JOIN);
    criteria.setFetchMode("items.type", FetchMode.JOIN);

    List<Attachment> result = criteria.list();

    if (result != null && result.size() > 0) {
        return result.get(0);
    } else {/* ww w .  j  a  v  a 2  s .com*/
        return null;
    }

}

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

@Override
public Customer findByKey(Integer key) {
    Criteria criteria = factory.getCurrentSession().createCriteria(Customer.class);
    criteria.add(Expression.eq("id", key));
    criteria.setFetchMode("address.province", FetchMode.JOIN);
    criteria.setFetchMode("address.amphur", FetchMode.JOIN);
    List<Customer> result = criteria.list();
    if (result != null && result.size() > 0) {
        return result.get(0);
    } else {/*from  ww w .j  a  va 2  s . co m*/
        return null;
    }
}

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

@Override
public Map findByQuery(CustomerQuery query) {
    int pageSize = Configs.PAGE_SIZE;
    Criteria criteria = factory.getCurrentSession().createCriteria(Customer.class);
    if (query.getCode() != null && !query.getCode().equals("")) {
        if (query.getCode().contains("*") || query.getCode().contains("?")) {
            criteria.add(Expression.like("code", query.getCode().replace("*", "%").replace("?", "_")));
        } else {//from www.  j  a  v a2  s.c  o  m
            criteria.add(Expression.eq("code", query.getCode()));
        }
    }
    if (query.getName() != null && !query.getName().equals("")) {
        if (query.getName().contains("*") || query.getName().contains("?")) {
            criteria.add(Expression.like("name", query.getName().replace("*", "%").replace("?", "_")));
        } else {
            criteria.add(Expression.eq("name", query.getName()));
        }
    }
    if (query.getCompany() != null && !query.getCompany().equals("")) {
        if (query.getCompany().contains("*") || query.getCompany().contains("?")) {
            criteria.add(Expression.like("company", query.getCompany().replace("*", "%").replace("?", "_")));
        } else {
            criteria.add(Expression.eq("company", query.getCompany()));
        }
    }
    if (query.getContactName() != null && !query.getContactName().equals("")) {
        if (query.getContactName().contains("*") || query.getContactName().contains("?")) {
            criteria.add(Expression.like("contact.contactName",
                    query.getContactName().replace("*", "%").replace("?", "_")));

        } else {
            criteria.add(Expression.eq("contact.contactName", query.getContactName()));
        }
    }
    if (query.getProvince() != null && query.getProvince() != 0) {
        criteria.createAlias("address.province", "p", JoinType.LEFT_OUTER_JOIN);
        criteria.add(Expression.eq("p.id", query.getProvince()));
    }
    List<CustomerType> types = new ArrayList<CustomerType>();
    if (query.getFlagCompany().equals("Y")) {
        types.add(CustomerType.C);
    }
    if (query.getFlagPersonal().equals("Y")) {
        types.add(CustomerType.P);
    }

    if (types.size() > 0) {
        criteria.add(Expression.in("customerType", types.toArray()));
    }

    long totalRecord = (long) criteria.setProjection(Projections.count(Projections.id().toString()))
            .uniqueResult();

    criteria.setProjection(null);

    int start = ((query.getPage() - 1) * pageSize);
    criteria.setFetchMode("address.province", FetchMode.JOIN);
    criteria.setFetchMode("address.amphur", FetchMode.JOIN);
    List<Customer> 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);

    System.out.println(pages.size());
    return data;
}

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

@Override
public Employee findByKey(Integer key) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(Employee.class);

    criteria.add(Restrictions.eq("id", key));
    criteria.setFetchMode("title", FetchMode.JOIN);
    criteria.setFetchMode("position", FetchMode.JOIN);
    criteria.setFetchMode("department", FetchMode.JOIN);
    criteria.setFetchMode("branch", FetchMode.JOIN);
    criteria.setFetchMode("address.province", FetchMode.JOIN);
    criteria.setFetchMode("address.amphur", FetchMode.JOIN);

    criteria.setFetchMode("educations", FetchMode.JOIN);
    criteria.setFetchMode("hobbies", FetchMode.JOIN);
    criteria.setFetchMode("experiences", FetchMode.JOIN);
    criteria.setFetchMode("educations.educationLevel", FetchMode.JOIN);
    criteria.setFetchMode("siblings", FetchMode.JOIN);
    criteria.setFetchMode("children", FetchMode.JOIN);
    criteria.setFetchMode("trainings", FetchMode.JOIN);
    criteria.setFetchMode("languages", FetchMode.JOIN);
    criteria.setFetchMode("languages.language", FetchMode.JOIN);
    criteria.setFetchMode("references", FetchMode.JOIN);
    criteria.setFetchMode("siblings.title", FetchMode.JOIN);
    criteria.setFetchMode("children.title", FetchMode.JOIN);
    criteria.setFetchMode("references.title", FetchMode.JOIN);

    List<Employee> result = criteria.list();
    if (result != null && result.size() > 0) {
        return result.get(0);
    } else {//  w  w  w . j  av  a2 s  .c o m
        return null;
    }
}

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

@Override
public Map findByQuery(EmployeeQuery query) {

    Session session = factory.getCurrentSession();
    Criteria criteria = session.createCriteria(Employee.class);
    if (query.getCode() != null && !query.getCode().equals("")) {
        if (query.getCode().contains("*") || query.getCode().contains("?")) {
            criteria.add(Expression.like("code", query.getCode().replace("*", "%").replace("?", "_")));
        } else {//  w  w w .  j  av  a  2 s.c o m
            criteria.add(Expression.eq("code", query.getCode()));
        }

    }
    if (query.getFirstName() != null && !query.getFirstName().equals("")) {
        if (query.getFirstName().contains("*") || query.getFirstName().contains("?")) {
            criteria.add(
                    Expression.like("firstName", query.getFirstName().replace("*", "%").replace("?", "_")));
        } else {
            criteria.add(Expression.eq("firstName", query.getFirstName()));
        }
    }
    if (query.getLastName() != null && !query.getLastName().equals("")) {
        if (query.getLastName().contains("*") || query.getLastName().contains("?")) {
            criteria.add(Expression.like("lastName", query.getLastName().replace("*", "%").replace("?", "_")));
        } else {
            criteria.add(Expression.eq("lastName", query.getLastName()));
        }
    }

    long totalRecord = (long) criteria.setProjection(Projections.count(Projections.id().toString()))
            .uniqueResult();
    long totalPage = totalRecord / Configs.PAGE_SIZE;
    if ((totalRecord % Configs.PAGE_SIZE) > 0) {
        totalPage++;
    }
    criteria.setProjection(null);
    int start = ((query.getPage() - 1) * Configs.PAGE_SIZE);//+ 1;
    List<Employee> result = criteria.setFetchMode("title", FetchMode.JOIN)
            .setFetchMode("position", FetchMode.JOIN).setFirstResult(start).setMaxResults(Configs.PAGE_SIZE)
            .setResultTransformer(Criteria.ROOT_ENTITY).list();
    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);

    System.out.println(pages.size());
    return data;
}