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:org.gbif.portal.dao.resources.impl.hibernate.DataResourceDAOImpl.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.resources.DataProviderDAO#findDataProviders(java.lang.String, boolean, int, int)
 *//* ww  w . j a  v  a2  s . c o  m*/
@SuppressWarnings("unchecked")
public Long countDataResources(final String nameStub, final boolean fuzzy, final DataProvider dataProvider,
        final BasisOfRecord basisOfRecord, final Date modifiedSince) {
    HibernateTemplate template = getHibernateTemplate();
    return ((Integer) template.execute(new HibernateCallback() {

        public Object doInHibernate(Session session) {
            Criteria criteria = session.createCriteria(DataResource.class, "dr");
            if (nameStub != null) {
                if (fuzzy) {
                    criteria = criteria.add(Restrictions.like("dr.name", nameStub, MatchMode.START));
                } else {
                    criteria = criteria.add(Restrictions.eq("dr.name", nameStub));
                }
            }
            if (dataProvider != null) {
                criteria = criteria.add(Restrictions.eq("dr.dataProvider", dataProvider));
            }
            if (basisOfRecord != null) {
                criteria = criteria.add(Restrictions.eq("dr.basisOfRecord", basisOfRecord));
            }
            if (modifiedSince != null) {
                criteria = criteria.add(Restrictions.ge("dp.modified", modifiedSince));
            }
            criteria = criteria.add(Restrictions.isNull("dr.deleted"));
            criteria.setFetchMode("dr.dataProvider", FetchMode.JOIN);
            criteria.setProjection(Projections.rowCount());
            return criteria.uniqueResult();
        }
    })).longValue();
}

From source file:org.gbif.portal.dao.resources.impl.hibernate.DataResourceDAOImpl.java

License:Open Source License

/**
 * @see org.gbif.portal.dao.resources.DataResourceDAO#findDataResources(java.lang.String, boolean, java.lang.Integer,
 *      java.lang.Integer)//from   ww w  . j av a  2 s.  co m
 */
@SuppressWarnings("unchecked")
public List<DataResource> findDataResources(final String nameStub, final boolean fuzzy,
        final DataProvider dataProvider, final BasisOfRecord basisOfRecord, final Date modifiedSince,
        final int startIndex, final int maxResults) {
    HibernateTemplate template = getHibernateTemplate();
    return (List<DataResource>) template.execute(new HibernateCallback() {

        public Object doInHibernate(Session session) {
            Criteria criteria = session.createCriteria(DataResource.class, "dr");
            if (nameStub != null) {
                if (fuzzy) {
                    criteria = criteria.add(Restrictions.like("dr.name", nameStub, MatchMode.START));
                } else {
                    criteria = criteria.add(Restrictions.eq("dr.name", nameStub));
                }
            }
            if (dataProvider != null) {
                criteria = criteria.add(Restrictions.eq("dr.dataProvider", dataProvider));
            }
            if (basisOfRecord != null) {
                criteria = criteria.add(Restrictions.eq("dr.basisOfRecord", basisOfRecord));
            }
            if (modifiedSince != null) {
                criteria = criteria.add(Restrictions.ge("dp.modified", modifiedSince));
            }
            criteria = criteria.add(Restrictions.isNull("dr.deleted"));
            criteria.setFetchMode("dr.dataProvider", FetchMode.JOIN);
            criteria.setCacheable(true);
            criteria.setMaxResults(maxResults);
            criteria.setFirstResult(startIndex);
            return criteria.list();
        }
    });
}

From source file:org.grails.orm.hibernate.cfg.GrailsHibernateUtil.java

License:Apache License

/**
 * Populates criteria arguments for the given target class and arguments map
 *
 * @param datastore the GrailsApplication instance
 * @param targetClass The target class/*ww w  . ja  v  a2  s.c  o  m*/
 * @param c The criteria instance
 * @param argMap The arguments map
 */
@SuppressWarnings("rawtypes")
public static void populateArgumentsForCriteria(AbstractHibernateDatastore datastore, Class<?> targetClass,
        Criteria c, Map argMap, ConversionService conversionService, boolean useDefaultMapping) {
    Integer maxParam = null;
    Integer offsetParam = null;
    if (argMap.containsKey(ARGUMENT_MAX)) {
        maxParam = conversionService.convert(argMap.get(ARGUMENT_MAX), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_OFFSET)) {
        offsetParam = conversionService.convert(argMap.get(ARGUMENT_OFFSET), Integer.class);
    }
    if (argMap.containsKey(ARGUMENT_FETCH_SIZE)) {
        c.setFetchSize(conversionService.convert(argMap.get(ARGUMENT_FETCH_SIZE), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_TIMEOUT)) {
        c.setTimeout(conversionService.convert(argMap.get(ARGUMENT_TIMEOUT), Integer.class));
    }
    if (argMap.containsKey(ARGUMENT_FLUSH_MODE)) {
        c.setFlushMode(convertFlushMode(argMap.get(ARGUMENT_FLUSH_MODE)));
    }
    if (argMap.containsKey(ARGUMENT_READ_ONLY)) {
        c.setReadOnly(ClassUtils.getBooleanFromMap(ARGUMENT_READ_ONLY, argMap));
    }
    String orderParam = (String) argMap.get(ARGUMENT_ORDER);
    Object fetchObj = argMap.get(ARGUMENT_FETCH);
    if (fetchObj instanceof Map) {
        Map fetch = (Map) fetchObj;
        for (Object o : fetch.keySet()) {
            String associationName = (String) o;
            c.setFetchMode(associationName, getFetchMode(fetch.get(associationName)));
        }
    }

    final int max = maxParam == null ? -1 : maxParam;
    final int offset = offsetParam == null ? -1 : offsetParam;
    if (max > -1) {
        c.setMaxResults(max);
    }
    if (offset > -1) {
        c.setFirstResult(offset);
    }
    if (ClassUtils.getBooleanFromMap(ARGUMENT_LOCK, argMap)) {
        c.setLockMode(LockMode.PESSIMISTIC_WRITE);
        c.setCacheable(false);
    } else {
        if (argMap.containsKey(ARGUMENT_CACHE)) {
            c.setCacheable(ClassUtils.getBooleanFromMap(ARGUMENT_CACHE, argMap));
        } else {
            cacheCriteriaByMapping(targetClass, c);
        }
    }

    final Object sortObj = argMap.get(ARGUMENT_SORT);
    if (sortObj != null) {
        boolean ignoreCase = true;
        Object caseArg = argMap.get(ARGUMENT_IGNORE_CASE);
        if (caseArg instanceof Boolean) {
            ignoreCase = (Boolean) caseArg;
        }
        if (sortObj instanceof Map) {
            Map sortMap = (Map) sortObj;
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, ignoreCase);
            }
        } else {
            final String sort = (String) sortObj;
            final String order = ORDER_DESC.equalsIgnoreCase(orderParam) ? ORDER_DESC : ORDER_ASC;
            addOrderPossiblyNested(datastore, c, targetClass, sort, order, ignoreCase);
        }
    } else if (useDefaultMapping) {
        Mapping m = GrailsDomainBinder.getMapping(targetClass);
        if (m != null) {
            Map sortMap = m.getSort().getNamesAndDirections();
            for (Object sort : sortMap.keySet()) {
                final String order = ORDER_DESC.equalsIgnoreCase((String) sortMap.get(sort)) ? ORDER_DESC
                        : ORDER_ASC;
                addOrderPossiblyNested(datastore, c, targetClass, (String) sort, order, true);
            }
        }
    }
}

From source file:org.grouter.domain.dao.ejb3.GenericEjb3DAO.java

License:Apache License

/**
 * {@inheritDoc}//from   ww w  .j av  a 2  s  . c  om
 */
public T findById(final ID id, final String... joinProps) {
    org.hibernate.Session session = ((HibernateEntityManager) getEntityManager()).getSession();
    org.hibernate.Criteria criteria = session.createCriteria(getPersistentClass());
    criteria.add(Restrictions.idEq(id));
    for (String prop : joinProps) {
        criteria.setFetchMode(prop, FetchMode.JOIN);
    }
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (T) criteria.uniqueResult();
}

From source file:org.grouter.domain.dao.ejb3.GenericEjb3DAO.java

License:Apache License

@SuppressWarnings("unchecked")
public T findById(final Class clazz, final T id, final String... joinProps) {
    org.hibernate.Session session = ((HibernateEntityManager) getEntityManager()).getSession();
    org.hibernate.Criteria criteria = session.createCriteria(getPersistentClass());
    criteria.add(Restrictions.idEq(id));
    for (String prop : joinProps) {
        criteria.setFetchMode(prop, FetchMode.JOIN);
    }//  w w  w. j  a  v  a  2 s . co m
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (T) criteria.uniqueResult();
}

From source file:org.grouter.domain.dao.spring.GenericHibernateDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public T findById(Class clazz, ID id, String... joinProps) {
    Criteria criteria = getSession().createCriteria(clazz);
    criteria.add(Restrictions.idEq(id));
    for (String prop : joinProps) {
        criteria.setFetchMode(prop, FetchMode.JOIN);
    }/*www .j  a va 2  s .com*/
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (T) criteria.uniqueResult();
}

From source file:org.grouter.domain.dao.spring.GenericHibernateDAO.java

License:Apache License

public List<T> findAllUsingFetchMode(final Class clazz, final FetchMode fetchMode, final String... joinProps) {
    Criteria criteria = getSession().createCriteria(clazz);
    for (String disJoinProp : joinProps) {
        criteria.setFetchMode(disJoinProp, fetchMode);
    }/*w w  w  .ja  va 2  s  .  c o m*/
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (List<T>) criteria.list();
}

From source file:org.grouter.domain.dao.spring.GenericHibernateDAO.java

License:Apache License

@SuppressWarnings("unchecked")
public T findById(final Class clazz, final T id, final String... joinProps) {
    Criteria criteria = getSession().createCriteria(clazz);
    criteria.add(Restrictions.idEq(id));
    for (String prop : joinProps) {
        criteria.setFetchMode(prop, FetchMode.JOIN);
    }/* w  w w.j a  va  2 s  . c o  m*/
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return (T) criteria.uniqueResult();
}

From source file:org.grouter.domain.dao.spring.MessageDAOImpl.java

License:Apache License

public List<Message> findMessagesBy(final Long messageId, final Date fromDate, final Date toDate,
        final String nodeId) {
    Criteria crit = getSession().createCriteria(getEntityClass());

    crit.setFetchMode("receivers", FetchMode.DEFAULT);
    crit.setFetchMode("node", FetchMode.DEFAULT);

    if (messageId == null && fromDate == null && toDate == null && nodeId == null) {
        return new ArrayList<Message>();
    }/*from w w w  .j a  v a  2s. c o m*/

    if (messageId != null) {
        crit.add(Restrictions.idEq(messageId));
        crit.addOrder(Order.asc("id"));

    }
    if (nodeId != null) {
        crit.add(Restrictions.eq("node.id", nodeId));
        crit.addOrder(Order.asc("id"));

    }
    if (fromDate != null) {
        crit.add(Restrictions.ge("auditInfo.createdOn", fromDate));
        crit.addOrder(Order.asc("auditInfo.createdOn"));
    }
    if (toDate != null) {
        crit.add(Restrictions.le("auditInfo.createdOn", toDate));
        crit.addOrder(Order.asc("auditInfo.createdOn"));
    }
    List<Message> messages = crit.list();
    return messages;
}

From source file:org.hoteia.qalingo.core.dao.AbstractGenericDao.java

License:Apache License

protected FetchPlan handleSpecificFetchMode(Criteria criteria, Object... params) {
    if (params != null) {
        FetchPlan globalFetchPlan = new FetchPlan(new ArrayList<SpecificFetchMode>());
        for (Object param : params) {
            if (param instanceof FetchPlan) {
                FetchPlan fetchPlan = (FetchPlan) param;
                for (Iterator<SpecificFetchMode> iterator = fetchPlan.getFetchModes().iterator(); iterator
                        .hasNext();) {/*from w  ww.  j  a  v  a2 s.  c o m*/
                    SpecificFetchMode specificFetchMode = (SpecificFetchMode) iterator.next();
                    if (!globalFetchPlan.getFetchModes().contains(specificFetchMode)) {
                        globalFetchPlan.getFetchModes().add(specificFetchMode);
                    }
                }
            }
        }

        if (globalFetchPlan != null && globalFetchPlan.getFetchModes() != null) {
            for (Iterator<SpecificFetchMode> iterator = globalFetchPlan.getFetchModes().iterator(); iterator
                    .hasNext();) {
                SpecificFetchMode specificFetchMode = (SpecificFetchMode) iterator.next();
                if (specificFetchMode.getRequiredAlias() != null) {
                    // TODO : Denis : check duplicate entry are manage or not
                    criteria.createAlias(specificFetchMode.getRequiredAlias().getAssocationPath(),
                            specificFetchMode.getRequiredAlias().getAlias(),
                            specificFetchMode.getRequiredAlias().getJoinType());
                }
                criteria.setFetchMode(specificFetchMode.getAssocationPath(), specificFetchMode.getFetchMode());
            }
            return globalFetchPlan;
        }

    }
    return null;
}