Example usage for org.hibernate Session createFilter

List of usage examples for org.hibernate Session createFilter

Introduction

In this page you can find the example usage for org.hibernate Session createFilter.

Prototype

@Deprecated
org.hibernate.Query createFilter(Object collection, String queryString);

Source Link

Document

Create a Query instance for the given collection and filter string.

Usage

From source file:com.bloatit.data.DaoMember.java

License:Open Source License

/**
 * [ Maybe it could be cool to have a parameter to list all the PUBLIC or
 * PROTECTED teams. ]//  w  ww  . ja va2  s  . c  o m
 *
 * @return All the teams this member is in. (Use a HQL query)
 */
public PageIterable<DaoTeam> getTeams() {
    final Session session = SessionManager.getSessionFactory().getCurrentSession();
    final Query filter = session.createFilter(getTeamMembership(), "select this.bloatitTeam order by login");
    final Query count = session.createFilter(getTeamMembership(), "select count(*)");
    return new QueryCollection<DaoTeam>(filter, count);
}

From source file:com.bloatit.data.DaoTeam.java

License:Open Source License

/**
 * @return all the member in this team. (Use a HQL query).
 *//*from  ww w  . ja v  a 2  s .  com*/
public PageIterable<DaoMember> getMembers() {
    final Session session = SessionManager.getSessionFactory().getCurrentSession();
    final Query filter = session.createFilter(getTeamMembership(), "select this.member order by login");
    final Query count = session.createFilter(getTeamMembership(), "select count(*)");
    return new QueryCollection<DaoMember>(filter, count);
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRED)
public List getSubFolders(final ExecutionContext context, final String folderURI) {
    return (List) executeCallback(new DaoCallback() {
        public Object execute() {
            final RepoFolder folder = getFolder(folderURI, false);
            List subfolders;//from   w ww.j ava2  s  .c o m
            if (folder == null || folder.getSubFolders() == null) {
                //return empty list for non-existing folder
                subfolders = new ArrayList();
            } else {
                List folders = getHibernateTemplate().executeFind(new HibernateCallback() {
                    public Object doInHibernate(Session session) throws HibernateException, SQLException {
                        return session.createFilter(folder.getSubFolders(), "where hidden = false").list();
                    }
                });

                subfolders = new ArrayList(folders.size());
                for (Iterator it = folders.iterator(); it.hasNext();) {
                    RepoFolder repoFolder = (RepoFolder) it.next();
                    subfolders.add(repoFolder.toClient());
                }

                SortingUtils.sortFoldersByName(getCollator(context), subfolders);
            }
            return subfolders;
        }
    });
}

From source file:com.zutubi.pulse.master.model.persistence.hibernate.HibernateChangelistDao.java

License:Apache License

public List<PersistentFileChange> getFiles(final PersistentChangelist changelist, final int offset,
        final int max) {
    return getHibernateTemplate().execute(new HibernateCallback<List<PersistentFileChange>>() {
        public List<PersistentFileChange> doInHibernate(Session session) throws HibernateException {
            Query queryObject = session.createFilter(changelist.getChanges(), "order by ordinal");
            queryObject.setFirstResult(offset);
            queryObject.setMaxResults(max);
            return queryObject.list();
        }/*from w w w.  ja  va 2s. c o  m*/
    });
}

From source file:corner.orm.tapestry.table.RelativePersistentBasicTableModel.java

License:Apache License

private Query createQuery(Session session, Collection c, String selectStr, String orderStr) {
    //TODO ?/* ww w  .j av  a2 s  .c om*/

    StringBuffer sb = new StringBuffer();
    if (selectStr != null) {
        sb.append(selectStr).append(" ");
    }

    Query query;
    if (callback != null) {
        //========  Example?.
        Criteria criteria = callback.createCriteria(session);

        //?
        callback.appendCriteria(criteria);
        String rootEntityName = ((CriteriaImpl) criteria).getEntityOrClassName();
        CriteriaQueryTranslator criteriaQuery = new CriteriaQueryTranslator(
                (SessionFactoryImplementor) session.getSessionFactory(), (CriteriaImpl) criteria,
                rootEntityName, Criteria.ROOT_ALIAS);
        String where = criteriaQuery.getWhereCondition();
        QueryParameters qps = criteriaQuery.getQueryParameters();

        //Criteria??where??
        if (where != null && where.length() > 0) {
            sb.append("where ").append(where).append(" ");
        }
        if (orderStr != null) {
            sb.append(orderStr);
        }
        query = session.createFilter(c, sb.toString()).setParameters(qps.getPositionalParameterValues(),
                qps.getPositionalParameterTypes());
    } else {
        if (orderStr != null) {
            sb.append(orderStr);
        }
        query = session.createFilter(c, sb.toString());

    }

    return query;

}

From source file:corner.service.EntityService.java

License:Apache License

/**
 * ?/*from   ww w  . ja  va2  s.co m*/
 * 
 * @param c ?
 * @return boolean
 * true: false:?
 */
public boolean isEmptyLazyCollection(final Collection c) {

    if (c == null) {
        return true;
    }

    int rows = ((Long) execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException, SQLException {
            Query query = session.createFilter(c, SELECT_COUNT_HQL_STR);
            return query.iterate().next();
        }
    })).intValue();

    return rows == 0;
}

From source file:edu.emory.library.tast.images.admin.ImagesBean.java

License:Open Source License

public String openImage() {

    editedImageId = Integer.parseInt(selectedImageId);

    // we come from list -> detail
    // so save the position in the list
    saveScrollPosition();/*from  w  w w . ja v a 2s. co m*/

    // open db
    Session sess = HibernateConn.getSession();
    Transaction transaction = sess.beginTransaction();

    // load image itself
    Image image = Image.loadById(editedImageId, sess);

    // load basic info to bean members
    imageTitle = image.getTitle();
    imageDescription = image.getDescription();
    imageExternalId = image.getExternalId();
    imageSource = image.getSource();
    imageDate = image.getDate();
    imageCreator = image.getCreator();
    imageLanguage = image.getLanguage();
    imageComments = image.getComments();
    imageReferences = image.getReferences();
    imageEmory = image.isEmory();
    imageEmoryLocation = image.getEmoryLocation();
    imageAuthorizationStatus = image.getAuthorizationStatus();
    imageImageStatus = image.getImageStatus();
    imageReadyToGo = image.isReadyToGo();
    imageCategoryId = image.getCategory().getId().intValue();

    // image properties
    imageWidth = image.getWidth();
    imageHeight = image.getHeight();
    imageSize = image.getSize();
    imageFileName = image.getFileName();
    imageMimeType = image.getMimeType();

    // linked voyage IDs
    imageVoyageIds = StringUtils.join("\n", image.getVoyageIds());

    // sort
    List regions = sess.createFilter(image.getRegions(), "order by this.name").list();
    List ports = sess.createFilter(image.getPorts(), "order by this.name").list();

    // selected regions
    int i = 0;
    selectedRegionsIds = new String[regions.size()];
    for (Iterator iter = regions.iterator(); iter.hasNext();) {
        Region dbRegion = (Region) iter.next();
        selectedRegionsIds[i++] = String.valueOf(dbRegion.getId());
    }

    // selected ports
    int j = 0;
    selectedPortsIds = new String[ports.size()];
    for (Iterator iter = ports.iterator(); iter.hasNext();) {
        Port dbPort = (Port) iter.next();
        selectedPortsIds[j++] = String.valueOf(dbPort.getId());
    }

    // close db
    transaction.commit();
    sess.close();

    // goto detail
    cleanAndPrepareDetailPage();
    return "detail";

}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

License:Open Source License

/**
 * Funziona SOLO CON IMPLEMENTAZIONE HIBERNATE
 * /*from  ww  w .ja  v  a  2  s  .c  o m*/
 * @param aList
 * @param aFilter
 * @return
 * @throws Exception
 */
public <T extends EntityBaseStandard> ArrayList<T> getFilteredList(Class<T> classObj, String aFilter)
        throws Exception {
    ArrayList<T> returnValue = null;

    EntityManagerFactory emf = null;
    EntityManager em = null;
    Session session = null;
    Criteria cri = null;
    try {
        /* Istanzio l'entity manager */
        emf = getEntityManagerFactory();
        em = emf.createEntityManager();

        session = (Session) em.getDelegate();

        org.hibernate.Query q = session.createQuery("from " + classObj.getName());
        q.setFirstResult(0);
        q.setMaxResults(100);
        List<T> resAll = q.list();

        org.hibernate.Query filterQuery = session.createFilter(resAll, aFilter);

        /* Effettuo la query */
        returnValue = (ArrayList) filterQuery.list();
    } catch (Exception e) {
        throw e;
    } finally {
        session = null;
        cri = null;
        em = null;
    }
    return returnValue;
}

From source file:org.eclipse.emf.cdo.server.internal.hibernate.HibernateStoreChunkReader.java

License:Open Source License

public List<Chunk> executeRead() {
    // get a transaction, the hibernateStoreAccessor is placed in a threadlocal
    // so all db access uses the same session.
    final Session session = getAccessor().getHibernateSession();

    // reread the revision as it is probably unreferenced
    final InternalCDORevision latestRevision = getLatestRevision(session);
    Object value = latestRevision.getValue(getFeature());
    if (value instanceof WrappedHibernateList) {
        value = ((WrappedHibernateList) value).getDelegate();
    }/*from  ww  w  .  j  ava  2 s  . c  o m*/

    // hibernate details...
    boolean useExtraLazyMode = false;
    boolean standardCDOList = false;
    QueryableCollection persister = null;
    CollectionEntry entry = null;
    if (value instanceof PersistentCollection) {
        final PersistentCollection persistentCollection = (PersistentCollection) value;
        persister = (QueryableCollection) ((SessionFactoryImplementor) session.getSessionFactory())
                .getCollectionPersister(persistentCollection.getRole());
        entry = ((SessionImplementor) session).getPersistenceContext().getCollectionEntry(persistentCollection);

        useExtraLazyMode = !persister.getElementType().isEntityType();
        if (useExtraLazyMode && ((PersistentCollection) value).hasQueuedOperations()) {
            session.flush();
        }
    } else {
        standardCDOList = true;
    }

    final List<Chunk> chunks = getChunks();
    for (Chunk chunk : chunks) {
        final int startIndex = chunk.getStartIndex();
        final int maxElements = chunk.size();
        if (standardCDOList) {
            // for eattributes just read them all, no chunking there...
            final CDOList list = (CDOList) value;
            if (startIndex >= list.size()) {
                return chunks;
            }
            for (int i = startIndex; i < startIndex + maxElements; i++) {
                if (i >= list.size()) {
                    break;
                }
                addToChunk(chunk, i - startIndex, list.get(i));
            }
        } else if (useExtraLazyMode) {
            if (getFeature() instanceof EReference) {
                for (int i = startIndex; i < startIndex + maxElements; i++) {
                    final Object object = persister.getElementByIndex(entry.getLoadedKey(), i,
                            (SessionImplementor) session, latestRevision);
                    // could happen if the index > size)
                    if (object == null) {
                        continue;
                    }
                    addToChunk(chunk, i - startIndex, object);
                }
            } else {
                // for eattributes just read them all, no chunking there...
                final List<?> list = (List<?>) value;
                if (startIndex >= list.size()) {
                    return chunks;
                }
                for (int i = startIndex; i < startIndex + maxElements; i++) {
                    if (i >= list.size()) {
                        break;
                    }
                    addToChunk(chunk, i - startIndex, list.get(i));
                }
            }
        } else {
            final Query filterQuery = session.createFilter(value, "");
            filterQuery.setMaxResults(maxElements);
            filterQuery.setFirstResult(startIndex);
            int i = 0;
            for (Object object : filterQuery.list()) {
                addToChunk(chunk, i++, object);
            }
        }
    }
    return chunks;
}

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

License:Open Source License

/**
 * Overridden because of access to size attribute. This version will try to
 * read the collection size without lading it if it is lazy loaded
 *//*from  w w  w. java  2s  .  c om*/
@Override
public int size() {
    // if we are not loaded yet, we return the size of the buffered lazy
    // load delegate

    if (!isLoaded() && delegateEList instanceof PersistableEList<?>
            && ((PersistableEList<?>) delegateEList).getDelegate() instanceof AbstractPersistentCollection) {
        final AbstractPersistentCollection abstractPersistentCollection = (AbstractPersistentCollection) ((PersistableEList<?>) delegateEList)
                .getDelegate();
        if (abstractPersistentCollection.wasInitialized()) {
            if (abstractPersistentCollection instanceof PersistentList) {
                return ((PersistentList) abstractPersistentCollection).size();
            } else if (abstractPersistentCollection instanceof PersistentMap) {
                return ((PersistentMap) abstractPersistentCollection).size();
            }
        } else if (cachedSize != null) {
            return cachedSize.intValue();
        }
        try {
            final Session s = (Session) ((AbstractPersistentCollection) ((PersistableEList<?>) delegateEList)
                    .getDelegate()).getSession();

            // now that we have the session, we can query the size of
            // the list without loading it
            s.flush();
            cachedSize = ((Long) s
                    .createFilter(((PersistableEList<?>) delegateEList).getDelegate(), "select count(*)").list()
                    .get(0));
            size = cachedSize.intValue();
            return cachedSize.intValue();
        } catch (Throwable t) {
            // ignore on purpose, let the call to super handle it
        }
    }

    // didnt work, so we simply call the parent version
    return super.size();
}