Example usage for org.hibernate FetchMode SELECT

List of usage examples for org.hibernate FetchMode SELECT

Introduction

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

Prototype

FetchMode SELECT

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

Click Source Link

Document

Fetch eagerly, using a separate select.

Usage

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 w w .  ja va 2  s.c o 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.cubeia.backoffice.users.dao.UserDAOImpl.java

License:Open Source License

private Criteria createFindUserCriteria(Long userId, Long operatorId, String name,
        Collection<UserStatus> includeStatuses, int offset, int limit, UserOrder order, boolean ascending) {

    Session hbSession = getHibernateSession();
    Criteria c = hbSession.createCriteria(User.class);
    c.createAlias("information", "information", JoinType.LEFT_OUTER_JOIN);
    c.setFetchMode("attributes", FetchMode.SELECT);

    if (userId != null) {
        c.add(eq("id", userId));
    }//w  ww  .j a  v  a2 s  .  c o m

    if (operatorId != null) {
        c.add(eq("operatorId", operatorId));
    }

    if (name != null && !name.isEmpty()) {
        c.add(Restrictions.disjunction().add(like("userName", name)).add(like("information.firstName", name))
                .add(like("information.lastName", name)));
    }

    if (includeStatuses != null) {
        c.add(Restrictions.in("status", includeStatuses));
    }

    if (order != null) {
        if (ascending) {
            c.addOrder(Order.asc(order.getColumnName()));
        } else {
            c.addOrder(Order.desc(order.getColumnName()));
        }
    }

    c.setFirstResult(offset);
    c.setMaxResults(limit);
    return c;
}

From source file:com.dell.asm.asmcore.asmmanager.db.TemplateDAO.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<TemplateEntity> getAllTemplates(List<SortParamParser.SortInfo> sortInfos,
        List<FilterParamParser.FilterInfo> filterInfos, PaginationInfo paginationInfo) {

    Session session = null;//w  w  w .j a va 2s  .  com
    Transaction tx = null;
    List<TemplateEntity> entityList = new ArrayList<>();

    try {
        int offset = paginationInfo.getOffset();
        int pageSize = paginationInfo.getLimit();

        session = _dao._database.getNewSession();
        tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(TemplateEntity.class);
        BaseDAO.addSortCriteria(criteria, sortInfos);
        List<FilterParamParser.FilterInfo> notFound = BaseDAO.addFilterCriteria(criteria, filterInfos,
                TemplateEntity.class);

        if (notFound != null && notFound.size() > 0) {
            criteria.createAlias("templateEntity", "templateEntityAlias");
            for (FilterParamParser.FilterInfo filterInfo : notFound) {
                criteria.add(Restrictions.eq("templateEntityAlias.deviceKey", filterInfo.getColumnName()));
                if (filterInfo.getColumnValue().size() == 1) {
                    criteria.add(Restrictions.eq("templateEntityAlias.deviceValue",
                            filterInfo.getColumnValue().get(0)));
                } else if (filterInfo.getColumnValue().size() > 1) {
                    criteria.add(
                            Restrictions.in("templateEntityAlias.deviceValue", filterInfo.getColumnValue()));
                }
            }
        }

        //criteria.setFirstResult((pageNumber - 1) * pageSize);
        criteria.setFirstResult(offset);
        criteria.setMaxResults(pageSize);
        criteria.setFetchMode("policyRefEntities", FetchMode.SELECT);

        entityList = criteria.list();

        //            Collection<PolicyRefEntity> dummy;
        //            for (TemplateEntity parm : entityList) {
        //              dummy = parm.getPolicyRefEntities();
        //              dummy.isEmpty();
        //            }

        // workaround for dupliacate templates
        //entityList.addAll(buildUniqueList(criteria.list()));

        // Commit transaction.
        tx.commit();
    } catch (Exception e) {
        logger.warn("Caught exception during get all templates: " + e);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception ex) {
            logger.warn("Unable to rollback transaction during get all templates: " + ex);
        }
        throw new AsmManagerInternalErrorException("Get All templates", "TemplateDAO", e);
    } finally {
        try {
            if (session != null) {
                session.close();
            }
        } catch (Exception ex) {
            logger.warn("Unable to close session during get all devices: " + ex);
        }
    }

    logger.warn("Template DAO get all templates size: " + entityList.size());
    return entityList;
}

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

License:Apache License

/**
 * Initializes a Criteria Query./*from   w  w  w .  jav  a  2s .co 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.hypersocket.local.LocalUserRepositoryImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)/*  w  w w  .j  a  va  2 s .c  o m*/
public List<?> getUsers(final Realm realm, final String searchPattern, final int start, final int length,
        final ColumnSort[] sorting) {
    return search(LocalUser.class, "name", searchPattern, start, length, sorting, new CriteriaConfiguration() {

        @Override
        public void configure(Criteria criteria) {
            criteria.add(Restrictions.eq("realm", realm));
            criteria.add(Restrictions.eq("deleted", false));
            criteria.add(Restrictions.eq("hidden", false));
            criteria.setFetchMode("groups", FetchMode.SELECT);
            criteria.setFetchMode("roles", FetchMode.SELECT);
            criteria.setFetchMode("properties", FetchMode.SELECT);
        }
    });
}

From source file:com.hypersocket.local.LocalUserRepositoryImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)/*  w  w w  .  j av a 2  s  .  com*/
public List<?> getGroups(final Realm realm, final String searchPattern, final int start, final int length,
        final ColumnSort[] sorting) {

    return search(LocalGroup.class, "name", searchPattern, start, length, sorting, new CriteriaConfiguration() {

        @Override
        public void configure(Criteria criteria) {
            criteria.add(Restrictions.eq("realm", realm));
            criteria.add(Restrictions.eq("deleted", false));
            criteria.add(Restrictions.eq("hidden", false));
            criteria.setFetchMode("users", FetchMode.SELECT);
            criteria.setFetchMode("roles", FetchMode.SELECT);
            criteria.setFetchMode("properties", FetchMode.SELECT);
        }
    });
}

From source file:com.hypersocket.network.NetworkResourceRepositoryImpl.java

License:Open Source License

@Override
public List<NetworkResource> search(Realm realm, String searchPattern, int start, int length,
        ColumnSort[] sorting, CriteriaConfiguration... configs) {
    return super.search(realm, searchPattern, start, length, sorting, new CriteriaConfiguration() {
        @Override/*ww w  .  ja va  2  s .  com*/
        public void configure(Criteria criteria) {
            criteria.setFetchMode("protocols", FetchMode.SELECT);
        }
    });
}

From source file:com.hypersocket.permissions.PermissionRepositoryImpl.java

License:Open Source License

@Override
@Transactional(readOnly = true)//  w w w .j a  v a 2 s  .c  om
public List<Role> searchRoles(final Realm realm, String searchPattern, int start, int length,
        ColumnSort[] sorting) {
    return search(Role.class, "name", searchPattern, start, length, sorting, new CriteriaConfiguration() {

        @Override
        public void configure(Criteria criteria) {
            criteria.add(Restrictions.eq("personalRole", false));
            criteria.add(Restrictions.eq("hidden", false));
            criteria.setFetchMode("permissions", FetchMode.SELECT);
            criteria.setFetchMode("principals", FetchMode.SELECT);
            criteria.setFetchMode("resources", FetchMode.SELECT);
            criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
            criteria.add(Restrictions.eq("realm", realm));
        }
    });
}

From source file:com.hypersocket.resource.AbstractAssignableResourceRepositoryImpl.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from   w w  w  . j av  a  2  s.c o m*/
public List<T> getResources(Realm realm) {

    Criteria crit = createCriteria(getResourceClass());
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    crit.setFetchMode("roles", FetchMode.SELECT);
    crit.add(Restrictions.eq("deleted", false));
    crit.add(Restrictions.eq("realm", realm));

    return (List<T>) crit.list();
}

From source file:com.hypersocket.resource.AbstractAssignableResourceRepositoryImpl.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<T> allResources() {

    Criteria crit = createCriteria(getResourceClass());
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    crit.setFetchMode("roles", FetchMode.SELECT);
    crit.add(Restrictions.eq("deleted", false));

    return (List<T>) crit.list();
}