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:org.ambraproject.admin.service.impl.AdminServiceImpl.java

License:Apache License

@Override
@Transactional/*w ww . j  av  a  2  s.  c o  m*/
public void updateVolume(final String volumeUri, final String displayName, final String issueCsv)
        throws IllegalArgumentException {
    hibernateTemplate.execute(new HibernateCallback() {
        @Override
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Volume volume = (Volume) session.createCriteria(Volume.class)
                    .add(Restrictions.eq("volumeUri", volumeUri)).setFetchMode("issues", FetchMode.JOIN)
                    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).uniqueResult();

            if (volume != null) {
                //check that we've only reordered the issue csv, not added or deleted
                String existingIssues = AdminServiceImpl.this.formatIssueCsv(volume.getIssues());
                for (String oldIssue : existingIssues.split(",")) {
                    if (!issueCsv.contains(oldIssue)) {
                        throw new IllegalArgumentException(
                                "Removed issue '" + oldIssue + "' from csv when updating volume");
                    }
                }
                for (String newIssue : issueCsv.split(",")) {
                    if (!existingIssues.contains(newIssue)) {
                        throw new IllegalArgumentException(
                                "Added issue '" + newIssue + "' to csv when updating volume");
                    }
                }

                volume.getIssues().clear();
                for (String issueUri : issueCsv.split(",")) {
                    Issue issue = (Issue) session.createCriteria(Issue.class)
                            .add(Restrictions.eq("issueUri", issueUri))
                            .setFetchMode("articleDois", FetchMode.SELECT)
                            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).uniqueResult();
                    if (issue != null) {
                        volume.getIssues().add(issue);
                    }
                }
                volume.setDisplayName(displayName);
                session.update(volume);
            }
            return null;
        }
    });
}

From source file:org.atemsource.atem.impl.hibernate.service.HibernateDao.java

License:Apache License

public Result getEntities(Class entityClass, int startIndex, int count, Sorting sorting,
        List<String> associationPaths) {
    try {/*from   w w w . ja  v  a 2 s.  com*/
        Criteria query = getSession().createCriteria(entityClass, "entity");
        if (count > 0) {
            query.setMaxResults(count);
        }
        if (startIndex >= 0) {
            query.setFirstResult(startIndex);
        }

        for (String associationPath : associationPaths) {
            query.setFetchMode(associationPath, FetchMode.SELECT);
        }
        List entities = query.list();
        Integer totalCount = entities.size();
        if (count <= 0) {
            totalCount = ((Number) getSession().createQuery("select count(*) from " + entityClass.getName())
                    .uniqueResult()).intValue();
        }
        return new Result(entities, totalCount);
    } catch (Exception e) {
        throw new TechnicalException("cannot get entities of type " + entityClass.getName(), e);
    }
}

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

License:Apache License

/**
 * Retrieves the fetch mode for the specified instance; otherwise returns the default FetchMode.
 *
 * @param object The object, converted to a string
 * @return The FetchMode/*  ww  w.  j a va2s .com*/
 */
public static FetchMode getFetchMode(Object object) {
    String name = object != null ? object.toString() : "default";
    if (name.equalsIgnoreCase(FetchMode.JOIN.toString()) || name.equalsIgnoreCase("eager")) {
        return FetchMode.JOIN;
    }
    if (name.equalsIgnoreCase(FetchMode.SELECT.toString()) || name.equalsIgnoreCase("lazy")) {
        return FetchMode.SELECT;
    }
    return FetchMode.DEFAULT;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateQuery.java

License:Apache License

@Override
public Query select(String property) {
    if (criteria != null)
        criteria.setFetchMode(property, FetchMode.SELECT);
    else if (detachedCriteria != null)
        detachedCriteria.setFetchMode(property, FetchMode.SELECT);
    return this;
}

From source file:org.codehaus.groovy.grails.orm.hibernate.query.AbstractHibernateQuery.java

License:Apache License

protected void applyFetchStrategies() {
    for (Map.Entry<String, FetchType> entry : fetchStrategies.entrySet()) {
        switch (entry.getValue()) {
        case EAGER:
            if (criteria != null)
                criteria.setFetchMode(entry.getKey(), FetchMode.JOIN);
            else if (detachedCriteria != null)
                detachedCriteria.setFetchMode(entry.getKey(), FetchMode.JOIN);
            break;
        case LAZY:
            if (criteria != null)
                criteria.setFetchMode(entry.getKey(), FetchMode.SELECT);
            else if (detachedCriteria != null)
                detachedCriteria.setFetchMode(entry.getKey(), FetchMode.SELECT);
            break;
        }/* w  w  w  .  j a v  a  2 s . co m*/
    }
}

From source file:org.eclipse.emf.teneo.hibernate.HbDataStore.java

License:Open Source License

/**
 * Extra lazy mapping for lists needs a real property for the list index and
 * a real inverse for the other side as well.
 * //from   w  ww  . ja v  a2s  .  co  m
 * This method iterates over all associations and adds an inverse for the
 * list and set mappings.
 */
protected void addExtraLazyInverseProperties() {
    final Map<String, PersistentClass> persistentClasses = new HashMap<String, PersistentClass>();
    for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) {
        final PersistentClass pc = (PersistentClass) pcs.next();
        if (isClassOrSuperClassEAVMapped(pc)) {
            continue;
        }
        persistentClasses.put(pc.getEntityName(), pc);
    }
    for (Iterator<?> pcs = getClassMappings(); pcs.hasNext();) {
        final PersistentClass pc = (PersistentClass) pcs.next();

        // copy to prevent concurrent modification
        final Iterator<?> propIt = pc.getPropertyIterator();
        final List<Property> props = new ArrayList<Property>();
        while (propIt.hasNext()) {
            final Property prop = (Property) propIt.next();
            props.add(prop);
        }

        for (Property prop : props) {
            EClass eClass = null;
            if (pc.getMetaAttribute(HbMapperConstants.FEATUREMAP_META) == null) {
                if (pc.getEntityName() != null) {
                    eClass = getEntityNameStrategy().toEClass(pc.getEntityName());
                } else {
                    eClass = EModelResolver.instance().getEClass(pc.getMappedClass());
                }
            }

            final EStructuralFeature ef = eClass == null ? null
                    : StoreUtil.getEStructuralFeature(eClass, prop.getName());
            if (ef != null && ef instanceof EReference && prop.getValue() instanceof Collection) {
                final Collection collection = (Collection) prop.getValue();
                final EReference eReference = (EReference) ef;

                // only work for extra lazy
                if (!collection.isExtraLazy()) {
                    continue;
                }

                final Value elementValue = collection.getElement();
                final PersistentClass elementPC;
                if (elementValue instanceof OneToMany) {
                    final OneToMany oneToMany = (OneToMany) elementValue;
                    elementPC = oneToMany.getAssociatedClass();
                } else if (elementValue instanceof ManyToOne) {
                    final ManyToOne mto = (ManyToOne) elementValue;
                    elementPC = persistentClasses.get(mto.getReferencedEntityName());
                } else {
                    continue;
                }

                if (isClassOrSuperClassEAVMapped(elementPC)) {
                    continue;
                }

                collection.setInverse(true);

                // and add an eopposite
                if (eReference.getEOpposite() == null) {

                    final Table collectionTable = collection.getCollectionTable();

                    if (isClassOrSuperClassEAVMapped(elementPC)) {
                        continue;
                    }

                    final Property inverseRefProperty = new Property();
                    inverseRefProperty.setName(StoreUtil.getExtraLazyInversePropertyName(ef));
                    final Map<Object, Object> metas = new HashMap<Object, Object>();
                    final MetaAttribute metaAttribute = new MetaAttribute(
                            HbConstants.SYNTHETIC_PROPERTY_INDICATOR);
                    metaAttribute.addValue("true");
                    metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute);
                    inverseRefProperty.setMetaAttributes(metas);
                    inverseRefProperty.setNodeName(inverseRefProperty.getName());
                    inverseRefProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName());
                    inverseRefProperty.setLazy(false);

                    final ManyToOne mto = new ManyToOne(getMappings(), collectionTable);
                    mto.setReferencedEntityName(pc.getEntityName());
                    mto.setLazy(false);
                    mto.setFetchMode(FetchMode.SELECT);

                    inverseRefProperty.setValue(mto);
                    final Iterator<?> it = collection.getKey().getColumnIterator();
                    while (it.hasNext()) {
                        final Column originalColumn = (Column) it.next();
                        // final Column newColumn = new
                        // Column(originalColumn.getName());
                        mto.addColumn(originalColumn);
                    }
                    mto.createForeignKey();

                    // now determine if a join should be created
                    if (collectionTable.getName().equalsIgnoreCase(elementPC.getTable().getName())) {
                        elementPC.addProperty(inverseRefProperty);
                    } else {
                        // create a join
                        final Join join = new Join();
                        join.setPersistentClass(elementPC);
                        join.setTable(collectionTable);
                        join.addProperty(inverseRefProperty);

                        final ManyToOne keyValue = new ManyToOne(getMappings(), collectionTable);
                        join.setKey(keyValue);
                        @SuppressWarnings("unchecked")
                        final Iterator<Column> keyColumns = collection.getElement().getColumnIterator();
                        while (keyColumns.hasNext()) {
                            keyValue.addColumn(keyColumns.next());
                        }
                        keyValue.setReferencedEntityName(elementPC.getEntityName());
                        keyValue.setTable(collectionTable);
                        keyValue.createForeignKey();

                        elementPC.addJoin(join);
                    }
                }

                // add an opposite index
                if (collection.isIndexed() && !collection.isMap()) {

                    Table collectionTable = collection.getCollectionTable();

                    IndexedCollection indexedCollection = (IndexedCollection) collection;

                    final Column column = (Column) indexedCollection.getIndex().getColumnIterator().next();

                    final Property indexProperty = new Property();
                    indexProperty.setName(StoreUtil.getExtraLazyInverseIndexPropertyName(ef));
                    final Map<Object, Object> metas = new HashMap<Object, Object>();
                    final MetaAttribute metaAttribute = new MetaAttribute(
                            HbConstants.SYNTHETIC_PROPERTY_INDICATOR);
                    metaAttribute.addValue("true");
                    metas.put(HbConstants.SYNTHETIC_PROPERTY_INDICATOR, metaAttribute);
                    indexProperty.setMetaAttributes(metas);
                    indexProperty.setNodeName(indexProperty.getName());
                    indexProperty.setPropertyAccessorName(SyntheticPropertyHandler.class.getName());
                    // always make this nullable, nullability is controlled
                    // by the main property
                    indexProperty.setOptional(true);

                    Join join = null;
                    @SuppressWarnings("unchecked")
                    final Iterator<Join> it = (Iterator<Join>) elementPC.getJoinIterator();
                    while (it.hasNext()) {
                        final Join foundJoin = it.next();
                        if (foundJoin.getTable().getName().equalsIgnoreCase(collectionTable.getName())) {
                            join = foundJoin;
                            collectionTable = join.getTable();
                            break;
                        }
                    }

                    final SimpleValue sv = new SimpleValue(getMappings(),
                            indexedCollection.getIndex().getTable());
                    sv.setTypeName("integer");
                    // final Column svColumn = new Column(column.getName());
                    sv.addColumn(column); // checkColumnExists(collectionTable,
                    // svColumn));
                    indexProperty.setValue(sv);
                    if (join != null) {
                        join.addProperty(indexProperty);
                    } else {
                        elementPC.addProperty(indexProperty);
                    }
                }
            }
        }
    }

}

From source file:org.eclipse.emf.teneo.hibernate.mapping.AnyEObjectType.java

License:Open Source License

public FetchMode getFetchMode(int i) {
    return FetchMode.SELECT;
}

From source file:org.emonocot.persistence.dao.hibernate.DaoImpl.java

License:Open Source License

/**
 *
 * @param t//from w w  w  .  java 2 s .  c  o m
 *            Set a the fetched object
 * @param fetch
 *            Set the name of the fetch profile
 */
protected void enableProfilePostQuery(final T t, final String fetch) {
    if (fetch != null && t != null) {
        Fetch[] fetchDefs = getProfile(fetch);
        if (fetchDefs == null || fetchDefs.length < 1) {
            return;
        }
        for (Fetch f : fetchDefs) {
            if (f.getMode().equals(FetchMode.SELECT)) {
                String association = f.getAssociation();
                if (association.indexOf(".") == -1) {
                    initializeProperty(t, f.getAssociation());
                } else {
                    List<String> associations = Arrays.asList(association.split("\\."));
                    initializeProperties(t, associations);
                }
            }
        }
    }
}

From source file:org.emonocot.persistence.dao.hibernate.TaxonDaoImpl.java

License:Open Source License

/**
 * @param t/*  ww  w . j  a  v  a  2  s  . co  m*/
 *            Set the taxon
 * @param fetch
 *            Set the fetch profile
 */
@Override
public final void enableProfilePostQuery(final Taxon t, final String fetch) {
    if (fetch != null && t != null) {
        for (Fetch f : getProfile(fetch)) {
            if (f.getMode().equals(FetchMode.SELECT)) {
                String association = f.getAssociation();
                if (association.indexOf(".") == -1) {
                    initializeProperty(t, f.getAssociation());
                } else {
                    List<String> associations = Arrays.asList(association.split("\\."));
                    initializeProperties(t, associations);
                }
            }
        }
    }
}

From source file:org.encuestame.persistence.dao.imp.AccountDaoImp.java

License:Apache License

public final List<UserAccount> retrieveListOwnerUsers(final Account account, final Integer maxResults,
        final Integer start) {
    final DetachedCriteria criteria = DetachedCriteria.forClass(UserAccount.class);
    criteria.add(Restrictions.eq("account", account));
    criteria.setFetchMode("secUserPermissions", FetchMode.SELECT);
    criteria.addOrder(Order.asc("enjoyDate"));
    getHibernateTemplate().setCacheQueries(true);
    return (List<UserAccount>) getHibernateTemplate().findByCriteria(criteria, start, maxResults);
}