Example usage for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY

List of usage examples for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY

Introduction

In this page you can find the example usage for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY.

Prototype

ResultTransformer DISTINCT_ROOT_ENTITY

To view the source code for org.hibernate.criterion CriteriaSpecification DISTINCT_ROOT_ENTITY.

Click Source Link

Document

Each row of results is a distinct instance of the root entity

Usage

From source file:org.opennms.web.svclayer.support.DefaultNodeListService.java

License:Open Source License

/** {@inheritDoc} */
public NodeListModel createNodeList(NodeListCommand command, boolean sanitizeLabels) {
    Collection<OnmsNode> onmsNodes = null;

    /*//from  w  w  w .j  a v a 2  s  .  c o  m
     * All search queries can be done solely with
     * criteria, so we build a common criteria object with common
     * restrictions and sort options.  Each specific search query
     * adds its own crtieria restrictions (if any).
     * 
     * A set of booleans is maintained for aliases that might be
     * added in muliple places to ensure we don't add the same alias
     * multiple times.
     */
    OnmsCriteria criteria = new OnmsCriteria(OnmsNode.class, "node");
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    criteria.add(Restrictions.ne("node.type", "D"));

    // Add additional criteria based on the command object
    addCriteriaForCommand(criteria, command);

    criteria.addOrder(Order.asc("node.label"));
    onmsNodes = m_nodeDao.findMatching(criteria);

    if (command.getNodesWithDownAggregateStatus()) {
        AggregateStatus as = new AggregateStatus(onmsNodes);
        onmsNodes = as.getDownNodes();
    }

    if (sanitizeLabels) {
        for (OnmsNode node : onmsNodes) {
            node.setLabel(WebSecurityUtils.sanitizeString(node.getLabel()));
        }
    }

    return createModelForNodes(command, onmsNodes);
}

From source file:org.opentaps.search.IndexingService.java

License:Open Source License

/**
 * Creates the hibernate search index for a given Entity class.
 * @param fullTextSession a <code>FullTextSession</code> value
 * @param entityClass a <code>Class</code> value
 *///from w ww .  j  av  a  2s.  c o  m
@SuppressWarnings("unchecked")
private void createIndexForEntity(FullTextSession fullTextSession, Class entityClass) {
    Criteria query = fullTextSession.createCriteria(entityClass)
            //load necessary associations
            .setFetchMode("distributor", FetchMode.JOIN)
            //distinct them (due to collection load)
            .setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
            //set flush mode, ensure it will write to disk on commit the transaction
            .setFlushMode(FlushMode.COMMIT)
            //minimize cache interaction
            .setCacheMode(CacheMode.IGNORE).setFetchSize(Session.FETCH_SIZE);
    //scroll in forward only
    ScrollableResults scroll = query.scroll(ScrollMode.FORWARD_ONLY);
    int batch = 0;
    while (scroll.next()) {
        batch++;
        fullTextSession.index(scroll.get(0));
        if (batch % Session.FETCH_SIZE == 0) {
            // batch flush index into session per FETCH_SIZE
            fullTextSession.flushToIndexes();
            fullTextSession.clear();
        }
    }
    // flush last changes
    fullTextSession.flushToIndexes();
    fullTextSession.getSearchFactory().optimize(entityClass);
}

From source file:org.shredzone.cilla.service.search.strategy.AbstractSearchStrategy.java

License:Open Source License

/**
 * Creates a {@link Criteria} object for the filter given in the
 * {@link SearchResultImpl}.//w ww.  ja  v a  2s  . c  o m
 */
protected Criteria createCriteria(SearchResultImpl result) throws CillaServiceException {
    Criteria crit = pageDao.criteria();
    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    crit.add(Restrictions.and(Restrictions.isNotNull("publication"),
            Restrictions.le("publication", result.getNow())));

    crit.add(
            Restrictions.or(Restrictions.isNull("expiration"), Restrictions.gt("expiration", result.getNow())));

    crit.add(Restrictions.eq("hidden", false));

    FilterModel filter = result.getFilter();
    if (filter != null) {
        if (filter.getCategory() != null) {
            // I'd prefer to use Restrictions.in instead, but this seems to be difficult.
            // http://stackoverflow.com/questions/407737/hibernate-criteria-querying-tables-in-nm-relationship
            Disjunction dis = Restrictions.disjunction();
            result.getEffectiveCategories().stream().mapToLong(Category::getId)
                    .forEach(id -> dis.add(Restrictions.idEq(id)));
            crit.createCriteria("categories").add(dis);
        }

        if (filter.getTag() != null) {
            long tagId = filter.getTag().getId();
            Disjunction dis = Restrictions.disjunction();

            // All pages with the requested tag
            crit.createAlias("tags", "tt");
            dis.add(Restrictions.eq("tt.id", tagId));

            // All pages with pictures in a gallery section having the requested tag
            DetachedCriteria subcrit = DetachedCriteria.forClass(GallerySection.class);
            subcrit.createCriteria("pictures").createCriteria("tags").add(Restrictions.idEq(tagId));
            subcrit.setProjection(Projections.distinct(Projections.property("page.id")));
            dis.add(Subqueries.propertyIn("id", subcrit));

            crit.add(dis);
        }

        if (filter.getCreator() != null) {
            crit.add(Restrictions.eq("creator", filter.getCreator()));
        }

        if (filter.getPage() != null) {
            crit.add(Restrictions.idEq(filter.getPage().getId()));
        }

        if (filter.getDate() != null) {
            DateRange dr = filter.getDate();
            PageOrder order = (filter.getOrder() != null ? filter.getOrder() : PageOrder.PUBLICATION);
            crit.add(Restrictions.between(order.getColumn(), dr.getFromDate().getTime(),
                    dr.getThruDate().getTime()));
        }

        if (filter.getQuery() != null) {
            // No challenge protected pages for context search, because protected
            // contents may be revealed in the search results.
            crit.add(Restrictions.isNull("challenge"));
        }
    }

    return crit;
}

From source file:org.squashtest.tm.service.internal.repository.hibernate.HibernateExecutionDao.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from www  .  java2  s. c o m*/
public List<Execution> findAllByTestCaseId(long testCaseId, PagingAndSorting pas) {
    Criteria crit = currentSession().createCriteria(Execution.class, EXECUTION)
            .createAlias("Execution.testPlan", TEST_PLAN, JoinType.LEFT_OUTER_JOIN)
            .createAlias("TestPlan.iteration", ITERATION, JoinType.LEFT_OUTER_JOIN)
            .createAlias(ITERATION_CAMPAIGN, CAMPAIGN, JoinType.LEFT_OUTER_JOIN)
            .createAlias(CAMPAIGN_PROJECT, PROJECT, JoinType.LEFT_OUTER_JOIN)
            .createAlias("Execution.referencedTestCase", TEST_CASE, JoinType.LEFT_OUTER_JOIN)
            .createAlias("TestPlan.testSuites", TEST_SUITE, JoinType.LEFT_OUTER_JOIN);

    crit.add(Restrictions.eq("TestCase.id", testCaseId));

    crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

    PagingUtils.addPaging(crit, pas);
    SortingUtils.addOrder(crit, pas);

    return crit.list();
}

From source file:org.tynamo.hibernate.services.HibernatePersistenceServiceImpl.java

License:Apache License

public <T> List<T> getInstances(Class<T> type, DetachedCriteria criteria) {
    criteria = alterCriteria(type, criteria);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return criteria.getExecutableCriteria(getSession()).list();
}

From source file:org.tynamo.hibernate.services.HibernatePersistenceServiceImpl.java

License:Apache License

public List getInstances(final Object example, final TynamoClassDescriptor classDescriptor) {
    //create Criteria instance
    DetachedCriteria searchCriteria = DetachedCriteria.forClass(example.getClass());
    searchCriteria = alterCriteria(example.getClass(), searchCriteria);

    //loop over the example object's PropertyDescriptors
    for (TynamoPropertyDescriptor propertyDescriptor : classDescriptor.getPropertyDescriptors()) {
        //only add a Criterion to the Criteria instance if this property is searchable
        if (propertyDescriptor.isSearchable()) {
            String propertyName = propertyDescriptor.getName();
            Class propertyClass = propertyDescriptor.getPropertyType();
            Object value = getPropertyAccess().get(example, propertyName);

            //only add a Criterion to the Criteria instance if the value for this property is non-null
            if (value != null) {
                if (String.class.isAssignableFrom(propertyClass) && ((String) value).length() > 0) {
                    searchCriteria.add(Restrictions.like(propertyName, value.toString(), MatchMode.ANYWHERE));
                }/*from   w  w  w  . ja va 2  s  .  co m*/
                /**
                 * 'one'-end of many-to-one, one-to-one
                 *
                 * Just match the identifier
                 */
                else if (propertyDescriptor.isObjectReference()) {
                    Serializable identifierValue = getIdentifier(value,
                            descriptorService.getClassDescriptor(propertyDescriptor.getBeanType()));
                    searchCriteria.createCriteria(propertyName).add(Restrictions.idEq(identifierValue));
                } else if (propertyClass.isPrimitive()) {
                    //primitive types: ignore zeroes in case of numeric types, ignore booleans anyway (TODO come up with something...)
                    if (!propertyClass.equals(boolean.class) && ((Number) value).longValue() != 0) {
                        searchCriteria.add(Restrictions.eq(propertyName, value));
                    }
                } else if (propertyDescriptor.isCollection()) {
                    //one-to-many or many-to-many
                    CollectionDescriptor collectionDescriptor = (CollectionDescriptor) propertyDescriptor;
                    TynamoClassDescriptor collectionClassDescriptor = descriptorService
                            .getClassDescriptor(collectionDescriptor.getElementType());
                    if (collectionClassDescriptor != null) {
                        String identifierName = collectionClassDescriptor.getIdentifierDescriptor().getName();
                        Collection<Serializable> identifierValues = new ArrayList<Serializable>();
                        Collection associatedItems = (Collection) value;
                        if (associatedItems != null && associatedItems.size() > 0) {
                            for (Object o : associatedItems) {
                                identifierValues.add(getIdentifier(o, collectionClassDescriptor));
                            }
                            //add a 'value IN collection' restriction
                            searchCriteria.createCriteria(propertyName)
                                    .add(Restrictions.in(identifierName, identifierValues));
                        }
                    }
                }
            }
        }
    }
    searchCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    // FIXME This won't work because the shadow proxy doesn't implement SessionImplementor
    // that session is casted to. Maybe we should inject SessionManager instead
    // and obtain the Session from it
    return searchCriteria.getExecutableCriteria(getSession()).list();
}

From source file:org.tynamo.hibernate.services.HibernatePersistenceServiceImpl.java

License:Apache License

public int count(Class type, DetachedCriteria detachedCriteria) {
    detachedCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    final DetachedCriteria criteria = alterCriteria(type, detachedCriteria);
    Criteria executableCriteria = criteria.getExecutableCriteria(getSession())
            .setProjection(Projections.rowCount());
    return ((Long) executableCriteria.uniqueResult()).intValue();
}

From source file:org.tynamo.hibernate.services.HibernatePersistenceServiceImpl.java

License:Apache License

public List getInstances(final DetachedCriteria detachedCriteria, final int startIndex, final int maxResults) {
    detachedCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    Criteria executableCriteria = detachedCriteria.getExecutableCriteria(getSession());
    if (startIndex >= 0) {
        executableCriteria.setFirstResult(startIndex);
    }/*from  w w  w.j  a v a 2s  . co  m*/
    if (maxResults > 0) {
        executableCriteria.setMaxResults(maxResults);
    }
    return executableCriteria.list();
}

From source file:org.yamj.core.database.dao.PlayerDao.java

License:Open Source License

public List<PlayerInfo> getPlayerList() {
    Session session = currentSession();//from   w  w w. j a v a  2 s.c om
    Criteria criteria = session.createCriteria(PlayerInfo.class);
    // http://stackoverflow.com/a/4645549/443283
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    return criteria.list();
}

From source file:reviewbot.repository.BookRepository.java

License:Creative Commons License

@Override
@SuppressWarnings("unchecked")
public List<Book> readAll() {
    Criteria criteria = getCurrentSession().createCriteria(Book.class);
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    criteria.addOrder(Order.asc("id"));

    List<Book> bookEntities = (List<Book>) criteria.list();
    List<Book> books = new ArrayList<Book>();

    for (Book book : bookEntities) {
        books.add(book);//  ww w .j  a v  a  2  s.  c  o  m
    }
    return books;
}