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.abssh.util.GenericDao.java

License:Apache License

/**
 * /*from  w w w .ja v a2  s . co  m*/
 * 
 * @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 {/* w w w . j  a  v  a2  s . co  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);
        }
    }

    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  va  2s .co m
 * @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.apress.progwt.server.dao.hibernate.UserDAOHibernateImpl.java

License:Apache License

/**
 * add all fetch mode concerns to the critera. without
 * DISTINCT_ROOT_ENTITY these fetches will create multiple rows
 * //from w ww  . j  a v a2 s .co m
 * If we join both schoolRankings & processTypes, we'll get duplicates
 * again. Fetch one of the collections with a SELECT and initialize
 * instead. Test in UserServiceImpl.testFetch()
 * 
 * Same with the process of each schoolRanking. Note, this is N+1
 * selects.
 * 
 * @param crit
 * @return
 */
private User fetchAllUser(DetachedCriteria crit) {
    crit.setFetchMode("schoolRankings", FetchMode.JOIN).setFetchMode("schoolRankings.school", FetchMode.JOIN)
            .setFetchMode("schoolRankings.process", FetchMode.SELECT)
            .setFetchMode("processTypes", FetchMode.SELECT)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    User rtn = (User) DataAccessUtils.uniqueResult(getHibernateTemplate().findByCriteria(crit));
    Hibernate.initialize(rtn.getProcessTypes());
    Hibernate.initialize(rtn.getRatingTypes());
    for (Application application : rtn.getSchoolRankings()) {
        Hibernate.initialize(application.getProcess());
        Hibernate.initialize(application.getRatings());
    }

    log.debug("fetched user: " + rtn.getNickname() + " ratings " + rtn.getRatingTypes().size());

    // Hibernate.initialize(rtn.getSchoolRankings());
    return rtn;

}

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 {/* w ww .jav  a 2s .  c om*/
        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 {//  w w  w . j a  va 2s .  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  ww  w .j a  va  2  s  .  co 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 {/*from  w w w  .j  a v  a  2s  . com*/
        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 {//from  w  ww . java  2  s.  co 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;
}

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

@Override
public Order findByKey(Integer key) {
    Criteria criteria = factory.getCurrentSession().createCriteria(Order.class);
    criteria.add(Restrictions.eq("id", key));

    criteria.setFetchMode("requestBy", FetchMode.JOIN);
    criteria.setFetchMode("approveBy", FetchMode.JOIN);
    criteria.setFetchMode("customer", FetchMode.JOIN);
    criteria.setFetchMode("shipper", FetchMode.JOIN);
    criteria.setFetchMode("address.province", FetchMode.JOIN);
    criteria.setFetchMode("address.amphur", FetchMode.JOIN);

    criteria.setFetchMode("items", FetchMode.JOIN);
    criteria.setFetchMode("items.product", FetchMode.JOIN);

    List<Order> result = criteria.list();
    if (result != null && result.size() > 0) {
        return result.get(0);
    } else {//from  w  ww. ja v  a  2 s .c o  m
        return null;
    }
}