Java 类org.hibernate.Criteria 实例源码

项目:NewsSystem    文件:NewsInfoDAOImpl.java   
/**
 * 根据条件查询指定新闻
 */
@Override
public List<?> getNewsInfoByConditionAndPage(NewsInfo condition, int page, int pageSize) {
    Session session = SessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(NewsInfo.class);
    if (condition != null) {
        if (condition.getTopic() != null && condition.getTopic().getId() != null ) {
            criteria.add(Restrictions.eq("topic.id", condition.getTopic().getId()));
        }
        if (condition.getTitle() != null && !"".equals(condition.getTitle())) {
            criteria.add(Restrictions.like("title", condition.getTitle(), MatchMode.ANYWHERE));
        }
    }
    criteria.setFirstResult(pageSize * (page - 1));
    criteria.setMaxResults(pageSize);
    criteria.addOrder(Order.desc("createDate"));
    return criteria.list();
}
项目:sjk    文件:AppDaoImpl.java   
@Override
public List<App> getAppsOfDropMarket(Session session, String marketName, Integer currentPage, Integer pageSize) {
    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.property("pkname"));
    proList.add(Projections.property("signatureSha1"));
    Criteria cri = session.createCriteria(App.class);
    cri.setProjection(proList);
    cri.setMaxResults(pageSize);
    cri.setFirstResult(HibernateHelper.firstResult(currentPage, pageSize));
    List<Object[]> list = HibernateHelper.list(cri);
    List<App> apps = null;
    if (list != null) {
        apps = new ArrayList<App>(list.size());
        for (Object[] obj : list) {
            App e = new App();
            e.setPkname((String) obj[0]);
            e.setSignatureSha1((String) obj[1]);
            apps.add(e);
        }
        list.clear();
    }
    return apps;
}
项目:ctsms    文件:ECRFDaoImpl.java   
@Override
protected Long handleFindMaxPosition(Long trialId, Long groupId) throws Exception {
    org.hibernate.Criteria ecrfCriteria = createEcrfCriteria(null);
    if (trialId != null) {
        ecrfCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
    }
    if (groupId != null) {
        ecrfCriteria.add(Restrictions.eq("group.id", groupId.longValue()));
    } else {
        ecrfCriteria.add(Restrictions.isNull("group.id"));
    }
    // if (visitId != null) {
    // ecrfCriteria.add(Restrictions.eq("visit.id", visitId.longValue()));
    // } else {
    // ecrfCriteria.add(Restrictions.isNull("visit.id"));
    // }
    ecrfCriteria.setProjection(Projections.max("position"));
    return (Long) ecrfCriteria.uniqueResult();
}
项目:admin-shiro    文件:AdminService.java   
@SuppressWarnings("unchecked")
public Pagination<AdminDO> pageAdminsByConditions(Integer pageIndex, Integer pageSize, Map<String, Object> params){
    //获取记录总数
    Criteria criteria = daoSupport.createCriteria(AdminDO.class);
    //相当于 select count(uid)
    criteria.setProjection(Projections.count("uid"));
    //设置查询条件
    if (Objects.nonNull(params)) {
        criteria.add(Restrictions.allEq(params));
    }
    criteria.add(Restrictions.eq("editEnable", Boolean.TRUE));
    Long total = (Long) criteria.uniqueResult();

    //开始查询列表,首先清除count查询所用Projection
    criteria.setProjection(null);
    criteria.setFirstResult((pageIndex - 1)* pageSize);
    criteria.setMaxResults(pageIndex * pageSize);
    List<AdminDO> admins = criteria.list();

    Pagination<AdminDO> pagination = new Pagination<AdminDO>(Long.valueOf(pageIndex), Long.valueOf(pageSize), total);
    pagination.setItems(admins);
    return pagination;
}
项目:sjk    文件:MarketDaoImpl.java   
@Override
public List<Market> listMarketRank() {
    ProjectionList proList = Projections.projectionList();
    proList.add(Projections.property("marketName"));
    proList.add(Projections.property("rank"));
    Criteria cri = getSession().createCriteria(Market.class);
    cri.setProjection(proList);
    List<Object[]> list = HibernateHelper.list(cri);
    List<Market> markets = null;
    if (list != null && !list.isEmpty()) {
        markets = new ArrayList<Market>(list.size());
        for (Object[] obj : list) {
            Market m = new Market();
            m.setMarketName((String) obj[0]);
            m.setRank((Integer) obj[1]);
            markets.add(m);
        }
    }
    return markets;
}
项目:dhus-core    文件:NetworkUsageDao.java   
public int countDownloadByUserSince (final User user, final Date date)
{
   Long result =
         getHibernateTemplate ().execute (new HibernateCallback<Long> ()
         {
            @Override
            public Long doInHibernate (Session session)
                  throws HibernateException, SQLException
            {
               Criteria criteria = session.createCriteria (
                     NetworkUsage.class);
               criteria.setProjection (Projections.rowCount ());
               criteria.add (Restrictions.eq ("isDownload", true));
               criteria.add (Restrictions.eq ("user", user));
               criteria.add (Restrictions.gt ("date", date));
               return (Long) criteria.uniqueResult ();
            }
         });
   return (result != null) ? result.intValue () : 0;
}
项目:ctsms    文件:CourseParticipationStatusEntryDaoImpl.java   
/**
 * @inheritDoc
 */
@Override
protected Collection<CourseParticipationStatusEntry> handleFindByStaffSection(Long staffId, Long sectionId, Boolean showCv, Boolean pass, Boolean showCvPreset, PSFVO psf)
        throws Exception
        {
    org.hibernate.Criteria courseParticipationStatusEntryCriteria = createCourseParticipationStatusEntryCriteria();
    SubCriteriaMap criteriaMap = new SubCriteriaMap(CourseParticipationStatusEntry.class, courseParticipationStatusEntryCriteria);
    if (staffId != null) {
        courseParticipationStatusEntryCriteria.add(Restrictions.eq("staff.id", staffId.longValue()));
    }
    if (showCvPreset != null) {
        criteriaMap.createCriteria("course").add(Restrictions.eq("showCvPreset", showCvPreset.booleanValue()));
    }
    if (sectionId != null) {
        courseParticipationStatusEntryCriteria.add(Restrictions.eq("section.id", sectionId.longValue()));
    }
    if (showCv != null) {
        courseParticipationStatusEntryCriteria.add(Restrictions.eq("showCv", showCv.booleanValue()));
    }
    if (pass != null) {
        criteriaMap.createCriteria("status").add(Restrictions.eq("pass", pass.booleanValue()));
    }
    CriteriaUtil.applyPSFVO(criteriaMap, psf);
    return courseParticipationStatusEntryCriteria.list();
        }
项目:sjk    文件:AppDaoImpl.java   
private Criteria searchByFilter(Short catalog, Integer subCatalog, String keywords, Integer id) {
    Criteria cri = getSession().createCriteria(App.class);

    if (catalog != null) {
        cri.add(Restrictions.eq("catalog", catalog));
    }
    if (subCatalog != null) {
        cri.add(Restrictions.eq("subCatalog", subCatalog));
    }
    if (id != null && id > 0) {
        cri.add(Restrictions.eq("id", id));
    }
    if (keywords != null && !keywords.isEmpty()) {
        cri.add(Restrictions.like("name", keywords, MatchMode.START));
    }
    return cri;
}
项目:FlashBoard    文件:QuizDaoImpl.java   
@Override
public Quiz getQuizByTitle(String quizTitle) {
    Session session = HibernateUtil.getSession();
    Criteria criteria;
    Quiz test = null;

    try {
        criteria = session.createCriteria(Quiz.class);
        //Adds like restriction to search for a particular username
        test = (Quiz)criteria.add(Restrictions.like("quizTitle", quizTitle)).uniqueResult();
    }
    catch(HibernateException he) {
        he.printStackTrace();
    }finally {
        session.close();
    }
    return test;
}
项目:sjk    文件:AppDaoImpl.java   
@Override
public List<Rollinfo> searchForRolling(Short catalog, Integer subCatalog, int page, int rows, String keywords,
        String sort, String order) {
    Criteria cri = getSession().createCriteria(Rollinfo.class);
    Criteria appCriteria = cri.createCriteria("app", JoinType.LEFT_OUTER_JOIN);
    if (catalog != null) {
        appCriteria.add(Restrictions.eq("catalog", catalog));
    }
    if (subCatalog != null) {
        appCriteria.add(Restrictions.eq("subCatalog", subCatalog));
    }

    if (keywords != null && !keywords.isEmpty()) {
        appCriteria.add(Restrictions.like("name", keywords, MatchMode.ANYWHERE));
    }

    if (sort != null && !sort.isEmpty()) {
        HibernateHelper.addOrder(appCriteria, sort, order);
    }
    cri.setMaxResults(rows);
    cri.setFirstResult(HibernateHelper.firstResult(page, rows));
    List<Rollinfo> list = HibernateHelper.list(cri);
    return list;
}
项目:ctsms    文件:ECRFDaoImpl.java   
@Override
protected long handleGetCount(Long trialId, Long groupId, Long visitId, Boolean active) throws Exception {
    org.hibernate.Criteria ecrfCriteria = createEcrfCriteria(null);
    if (trialId != null) {
        ecrfCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
    }
    if (groupId != null) {
        ecrfCriteria.add(Restrictions.or(Restrictions.eq("group.id", groupId.longValue()),
                Restrictions.isNull("group.id")));
    }
    if (visitId != null) {
        ecrfCriteria.add(Restrictions.or(Restrictions.eq("visit.id", visitId.longValue()),
                Restrictions.isNull("visit.id")));
    }
    if (active != null) {
        ecrfCriteria.add(Restrictions.eq("active", active.booleanValue()));
    }
    return (Long) ecrfCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
项目:lemon    文件:HibernateGenericDao.java   
/**
 * 根据entityClass,生成带排序的Criteria.
 * 
 * @param <T>
 *            实体类型
 * @param entityClass
 *            类型
 * @param orderBy
 *            排序字段名
 * @param isAsc
 *            是否正序
 * @param criterions
 *            条件
 * @return Criteria
 */
public <T> Criteria createCriteria(Class<T> entityClass, String orderBy,
        boolean isAsc, Criterion... criterions) {
    if (StringUtils.hasText(orderBy)) {
        Criteria criteria = createCriteria(entityClass, criterions);

        if (isAsc) {
            criteria.addOrder(Order.asc(orderBy));
        } else {
            criteria.addOrder(Order.desc(orderBy));
        }

        return criteria;
    } else {
        return createCriteria(entityClass, criterions);
    }
}
项目:dswork    文件:HibernateBaseDao.java   
/**
 * 分页查询数据
 * @param filters Map&lt;String, Object&gt;查询参数和条件数据<br />
 * &nbsp; &nbsp; 需要重写queryParam(Criteria criteria)方法
 * @return Page
 */
public List<E> queryList(final PageRequest pageRequest)
{
    return (List<E>)getHibernateTemplate().execute(new HibernateCallback()
    {
        public List<E> doInHibernate(Session session) throws HibernateException//, SQLException
        {
            Criteria criteria = session.createCriteria(getEntityClass());
            if (pageRequest.getFilters() instanceof Map)
            {
                queryParam((Map)pageRequest.getFilters(), criteria);
            }
            return queryList(criteria, pageRequest);
        }
    });
}
项目:hska-vis-legacy    文件:GenericHibernateDAO.java   
@SuppressWarnings("unchecked")
public E getObjectByName(String name) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    try
    {
        E entity = null;
        session.beginTransaction();
           Criteria crit = session.createCriteria(entityClass);
           crit.add(Restrictions.eq("name",name));
           List<E> resultList = crit.list();
           if (resultList.size() > 0) {
            entity = (E) crit.list().get(0);
           }
           session.getTransaction().commit();
           return entity;
    }
    catch (HibernateException e)
    {
        //log.error("Hibernate Exception" + e.getMessage());
        session.getTransaction().rollback();
        throw new RuntimeException(e);
    }
}
项目:Layer-Query    文件:CustomCriteriaQueryTranslator.java   
/**
     * REVISAR NIKOLAS
     */
    @Override
    public String[] getColumns(
            String propertyName,
            Criteria subcriteria) throws HibernateException {
//      return getPropertyMapping( getEntityName( subcriteria, propertyName ) )
//              .toColumns(
//                      getSQLAlias( subcriteria, propertyName ),
//                      getPropertyName( propertyName )
//              );
        String alias = getSQLAlias( subcriteria, propertyName );
        String property = getPropertyName( propertyName );
        String _root = AbstractEntityPersister.generateTableAlias(
                alias,
                0
        );

        return new String[]{_root+"."+property};
    }
项目:ctsms    文件:ProbandListStatusEntryDaoImpl.java   
@Override
protected ProbandListStatusEntry handleFindRecentStatus(
        Long trialId, Long probandId, Timestamp maxRealTimestamp)
                throws Exception {
    org.hibernate.Criteria statusEntryCriteria = createStatusEntryCriteria(null);
    if (maxRealTimestamp != null) {
        statusEntryCriteria.add(Restrictions.le("realTimestamp", maxRealTimestamp));
    }
    if (trialId != null || probandId != null) {
        Criteria listEntryCriteria = statusEntryCriteria.createCriteria("listEntry");
        if (trialId != null) {
            listEntryCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
        }
        if (probandId != null) {
            listEntryCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
        }
    }
    statusEntryCriteria.addOrder(Order.desc("realTimestamp"));
    statusEntryCriteria.addOrder(Order.desc("id"));
    statusEntryCriteria.setMaxResults(1);
    return (ProbandListStatusEntry) statusEntryCriteria.uniqueResult();
}
项目:Layer-Query    文件:CustomCriteriaQueryTranslator.java   
@Override
public String getColumn(Criteria criteria, String propertyName) {
    String[] cols = getColumns( propertyName, criteria );
    if ( cols.length != 1 ) {
        throw new QueryException( "property does not map to a single column: " + propertyName );
    }
    return cols[0];
}
项目:lams    文件:CriteriaQueryTranslator.java   
/**
 * Get the a typed value for the given property value.
 */
@Override
public TypedValue getTypedValue(Criteria subcriteria, String propertyName, Object value) throws HibernateException {
    // Detect discriminator values...
    if ( value instanceof Class ) {
        final Class entityClass = (Class) value;
        final Queryable q = SessionFactoryHelper.findQueryableUsingImports( sessionFactory, entityClass.getName() );
        if ( q != null ) {
            final Type type = q.getDiscriminatorType();
            String stringValue = q.getDiscriminatorSQLValue();
            if ( stringValue != null
                    && stringValue.length() > 2
                    && stringValue.startsWith( "'" )
                    && stringValue.endsWith( "'" ) ) {
                // remove the single quotes
                stringValue = stringValue.substring( 1, stringValue.length() - 1 );
            }

            // Convert the string value into the proper type.
            if ( type instanceof StringRepresentableType ) {
                final StringRepresentableType nullableType = (StringRepresentableType) type;
                value = nullableType.fromStringValue( stringValue );
            }
            else {
                throw new QueryException( "Unsupported discriminator type " + type );
            }
            return new TypedValue( type, value );
        }
    }
    // Otherwise, this is an ordinary value.
    return new TypedValue( getTypeUsingProjection( subcriteria, propertyName ), value );
}
项目:lams    文件:LogicalExpression.java   
@Override
public TypedValue[] getTypedValues(Criteria criteria, CriteriaQuery criteriaQuery) {
    final TypedValue[] lhsTypedValues = lhs.getTypedValues( criteria, criteriaQuery );
    final TypedValue[] rhsTypedValues = rhs.getTypedValues( criteria, criteriaQuery );

    final TypedValue[] result = new TypedValue[ lhsTypedValues.length + rhsTypedValues.length ];
    System.arraycopy( lhsTypedValues, 0, result, 0, lhsTypedValues.length );
    System.arraycopy( rhsTypedValues, 0, result, lhsTypedValues.length, rhsTypedValues.length );
    return result;
}
项目:FeedbackCollectionAndMgmtSystem    文件:HibernateTokenRepositoryImpl.java   
@Override
public void removeUserTokens(String username) {
    logger.info("Removing Token if any for user : {}", username);
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("userEmail", username));
    UserSessions userSession = (UserSessions) crit.uniqueResult();
    if (userSession != null) {
        logger.info("rememberMe was selected");
        delete(userSession);
    }

}
项目:sjk    文件:TagAppDaoImpl.java   
private List<App> getTagApps(Integer[] ids) {
    Criteria cri = getSession().createCriteria(App.class);
    cri.add(Restrictions.eq("hidden", false));
    cri.add(Restrictions.in("id", ids));
    List<App> list = HibernateHelper.list(cri);
    return list;
}
项目:Layer-Query    文件:CustomCriteriaQueryTranslator.java   
/**
 * Get the names of the columns constrained
 * by this criterion.
 */
@Override
public String[] getColumnsUsingProjection(
        Criteria subcriteria,
        String propertyName) throws HibernateException {

    //first look for a reference to a projection alias
    final Projection projection = rootCriteria.getProjection();
    String[] projectionColumns = null;
    if ( projection != null ) {
        projectionColumns = ( projection instanceof EnhancedProjection ?
                ( (EnhancedProjection) projection ).getColumnAliases( propertyName, 0, rootCriteria, this ) :
                projection.getColumnAliases( propertyName, 0 )
        );
    }
    if ( projectionColumns == null ) {
        //it does not refer to an alias of a projection,
        //look for a property
        try {
            return getColumns( propertyName, subcriteria );
        }
        catch (HibernateException he) {
            //not found in inner query , try the outer query
            if ( outerQueryTranslator != null ) {
                return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName );
            }
            else {
                throw he;
            }
        }
    }
    else {
        //it refers to an alias of a projection
        return projectionColumns;
    }
}
项目:gitplex-mit    文件:DefaultPersistManager.java   
@Sessional
@Override
public void exportData(File exportDir, int batchSize) {
    Session session = sessionFactory.openSession();
    for (Class<?> entityType: getEntityTypes(sessionFactory)) {
        logger.info("Exporting table '" + entityType.getSimpleName() + "'...");

        logger.info("Querying table ids...");

        Criteria criteria = session.createCriteria(entityType, "entity")
                .setProjection(Projections.property("entity.id")).addOrder(Order.asc("id"));
        @SuppressWarnings("unchecked")
        List<Long> ids = criteria.list();
        int count = ids.size();

        for (int i=0; i<count/batchSize; i++) {
            exportEntity(session, entityType, ids, i*batchSize, batchSize, batchSize, exportDir);
            // clear session to free memory
            session.clear();
        }

        if (count%batchSize != 0) {
            exportEntity(session, entityType, ids, count/batchSize*batchSize, count%batchSize, batchSize, exportDir);
        }
        logger.info("");
    }
}
项目:ctsms    文件:ProbandStatusEntryDaoImpl.java   
@Override
protected long handleGetCount(Long probandId) throws Exception {
    Criteria statusEntryCriteria = createStatusEntryCriteria();
    if (probandId != null) {
        statusEntryCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
    }
    return (Long) statusEntryCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
项目:sjk    文件:MarketDaoImpl.java   
@Override
public Market getByName(Session session, String marketName) {
    Criteria cri = session.createCriteria(Market.class);
    cri.add(Restrictions.eq("marketName", marketName));
    cri.setCacheable(true);
    return (Market) cri.uniqueResult();
}
项目:ctsms    文件:StaffStatusEntryDaoImpl.java   
@Override
protected Collection<StaffStatusEntry> handleFindByStaff(Long staffId,
        PSFVO psf) throws Exception {
    Criteria statusEntryCriteria = createStatusEntryCriteria();
    SubCriteriaMap criteriaMap = new SubCriteriaMap(StaffStatusEntry.class, statusEntryCriteria);
    if (staffId != null) {
        statusEntryCriteria.add(Restrictions.eq("staff.id", staffId.longValue()));
    }
    CriteriaUtil.applyPSFVO(criteriaMap, psf);
    return statusEntryCriteria.list();
}
项目:lams    文件:PropertyProjection.java   
@Override
public String toSqlString(Criteria criteria, int position, CriteriaQuery criteriaQuery) throws HibernateException {
    final StringBuilder buf = new StringBuilder();
    final String[] cols = criteriaQuery.getColumns( propertyName, criteria );
    for ( int i=0; i<cols.length; i++ ) {
        buf.append( cols[i] )
                .append( " as y" )
                .append( position + i )
                .append( '_' );
        if (i < cols.length -1) {
            buf.append( ", " );
        }
    }
    return buf.toString();
}
项目:lams    文件:SubqueryExpression.java   
private SessionImplementor deriveRootSession(Criteria criteria) {
    if ( criteria instanceof CriteriaImpl ) {
        return ( (CriteriaImpl) criteria ).getSession();
    }
    else if ( criteria instanceof CriteriaImpl.Subcriteria ) {
        return deriveRootSession( ( (CriteriaImpl.Subcriteria) criteria ).getParent() );
    }
    else {
        // could happen for custom Criteria impls.  Not likely, but...
        //      for long term solution, see HHH-3514
        return null;
    }
}
项目:lams    文件:SubqueryExpression.java   
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
    final StringBuilder buf = new StringBuilder( toLeftSqlString( criteria, criteriaQuery ) );
    if ( op != null ) {
        buf.append( ' ' ).append( op ).append( ' ' );
    }
    if ( quantifier != null ) {
        buf.append( quantifier ).append( ' ' );
    }

    final SessionFactoryImplementor factory = criteriaQuery.getFactory();
    final OuterJoinLoadable persister =
            (OuterJoinLoadable) factory.getEntityPersister( criteriaImpl.getEntityOrClassName() );

    createAndSetInnerQuery( criteriaQuery, factory );
    criteriaImpl.setSession( deriveRootSession( criteria ) );

    final CriteriaJoinWalker walker = new CriteriaJoinWalker(
            persister,
            innerQuery,
            factory,
            criteriaImpl,
            criteriaImpl.getEntityOrClassName(),
            criteriaImpl.getSession().getLoadQueryInfluencers(),
            innerQuery.getRootSQLALias()
    );

    return buf.append( '(' ).append( walker.getSQLString() ).append( ')' ).toString();
}
项目:lemon    文件:HibernatePagingDao.java   
/**
 * 分页查询函数,根据entityClass和page参数进行查询.
 * 
 * @param <T>
 *            实体类型
 * @param entityClass
 *            实体类型
 * @param page
 *            分页里包含的各种参数
 * @param criterions
 *            条件
 * @return 含总记录数和当前页数据的Page对象.
 */
@Transactional(readOnly = true)
public <T> Page pagedQuery(Class<T> entityClass, Page page,
        Criterion... criterions) {
    Criteria criteria = createCriteria(entityClass, criterions);

    if (page.isOrderEnabled()) {
        criteria = createCriteria(entityClass, criterions);

        for (int i = 0; i < page.getOrderBys().size(); i++) {
            String orderBy = page.getOrderBys().get(i);
            String order = page.getOrders().get(i);

            if ("ASC".equals(page.getOrders().get(i))) {
                criteria.addOrder(Order.asc(orderBy));
            } else {
                criteria.addOrder(Order.desc(orderBy));
            }
        }
    }

    Page resultPage = this.pagedQuery(criteria, page.getPageNo(),
            page.getPageSize());
    resultPage.setOrderBys(page.getOrderBys());
    resultPage.setOrders(page.getOrders());

    return resultPage;
}
项目:sjk    文件:MarketAppDaoImpl.java   
@Override
public List<MarketApp> getByPackagename(Session sess, String pkname) {
    Criteria cri = sess.createCriteria(MarketApp.class);
    cri.add(Restrictions.eq("pkname", pkname));
    List<MarketApp> list = HibernateHelper.list(cri);
    return list;
}
项目:lemon    文件:HibernateGenericDao.java   
/**
 * 根据entityClass生成对应类型的Criteria.
 * 
 * @param entityClass
 *            实体类型
 * @param criterions
 *            条件
 * @return Criteria
 */
public Criteria createCriteria(Class entityClass, Criterion... criterions) {
    Criteria criteria = this.getSession().createCriteria(entityClass);

    for (Criterion c : criterions) {
        criteria.add(c);
    }

    return criteria;
}
项目:lams    文件:CriteriaQueryTranslator.java   
/**
 * Get the names of the columns constrained
 * by this criterion.
 */
@Override
public String[] getColumnsUsingProjection(
        Criteria subcriteria,
        String propertyName) throws HibernateException {

    //first look for a reference to a projection alias
    final Projection projection = rootCriteria.getProjection();
    String[] projectionColumns = null;
    if ( projection != null ) {
        projectionColumns = ( projection instanceof EnhancedProjection ?
                ( ( EnhancedProjection ) projection ).getColumnAliases( propertyName, 0, rootCriteria, this ) :
                projection.getColumnAliases( propertyName, 0 )
        );
    }
    if ( projectionColumns == null ) {
        //it does not refer to an alias of a projection,
        //look for a property
        try {
            return getColumns( propertyName, subcriteria );
        }
        catch ( HibernateException he ) {
            //not found in inner query , try the outer query
            if ( outerQueryTranslator != null ) {
                return outerQueryTranslator.getColumnsUsingProjection( subcriteria, propertyName );
            }
            else {
                throw he;
            }
        }
    }
    else {
        //it refers to an alias of a projection
        return projectionColumns;
    }
}
项目:sjk    文件:TagDaoImpl.java   
@Override
public List<Tag> list(TagType tagType) {
    Criteria cri = getSession().createCriteria(Tag.class);
    if (null != tagType) {
        // 注释原因: tagType是枚举类型(int) Tag实体tagType属性是Short类型 不能直接把int 转化成
        // short 类型
        cri.add(Restrictions.eq("tagType", Short.valueOf(tagType.getVal())));
    }
    cri.addOrder(Order.desc("rank"));
    return HibernateHelper.list(cri);
}
项目:sdudoc    文件:BookDaoImpl.java   
@Override
public Pager<Book> searchByAuthor(String author, int pageNo, int pageSize) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    criteria.add(Restrictions.like("authors", "%"+author+"%"));
    long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
    criteria.setProjection(null);
//  criteria.addOrder(Order.desc("clickTimes"));
    criteria.setFirstResult((pageNo - 1) * pageSize);
    criteria.setMaxResults(pageSize);
    List<Book> results = criteria.list();
    Pager<Book> page=new Pager<Book>(pageSize, pageNo, recordTotal, results);
    return page;
}
项目:sdudoc    文件:BookDaoImpl.java   
public Pager<Book> showBookByClickTimes(int pageNo, int pageSize) {
    Session session = sessionFactory.getCurrentSession();
    Criteria criteria = session.createCriteria(Book.class);
    long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
    criteria.setProjection(null);
    criteria.addOrder(Order.desc("clickTimes"));
    criteria.setFirstResult((pageNo - 1) * pageSize);
    criteria.setMaxResults(pageSize);
    List<Book> results = criteria.list();
    Pager<Book> page=new Pager<Book>(pageSize, pageNo, recordTotal, results);
    return page;

}
项目:ctsms    文件:StaffStatusEntryDaoImpl.java   
@Override
protected Collection<StaffStatusEntry> handleFindByStaffInterval(
        Long staffId, Timestamp from, Timestamp to, Boolean staffActive)
                throws Exception {
    Criteria statusEntryCriteria = createStatusEntryCriteria();
    CriteriaUtil.applyStopOpenIntervalCriterion(statusEntryCriteria, from, to, null);
    if (staffActive != null) {
        statusEntryCriteria.createCriteria("type", CriteriaSpecification.INNER_JOIN).add(Restrictions.eq("staffActive", staffActive.booleanValue()));
    }
    if (staffId != null) {
        statusEntryCriteria.add(Restrictions.eq("staff.id", staffId.longValue()));
    }
    return statusEntryCriteria.list();
}
项目:ipf-flow-manager    文件:Query.java   
@SuppressWarnings("unchecked")
public List<Flow> listFlows(String query, Criteria criteria) {
    if (criteria == null) {
        return listFlows(query);
    }
    return createFullTextQuery(query).setCriteriaQuery(criteria).list();
}
项目:sjk    文件:CatalogConvertorDaoImpl.java   
@Override
public List<CatalogConvertor> searchByMarketNameAndCatalog(String marketName, short catalog) {
    Criteria cri = getSession().createCriteria(CatalogConvertor.class);
    cri.add(Restrictions.eq("marketName", marketName));
    cri.add(Restrictions.eq("catalog", catalog));
    List<CatalogConvertor> list = HibernateHelper.list(cri);
    return list;
}
项目:ctsms    文件:MoneyTransferDaoImpl.java   
@Override
protected Collection<MoneyTransfer> handleFindByProbandNoTrialMethodCostTypePaid(Long probandId, PaymentMethod method, String costType, Boolean paid) throws Exception
{
    org.hibernate.Criteria moneyTransferCriteria = createMoneyTransferCriteria("moneyTransfer");
    if (method != null) {
        moneyTransferCriteria.add(Restrictions.eq("method", method));
    }
    if (paid != null) {
        moneyTransferCriteria.add(Restrictions.eq("paid", paid.booleanValue()));
    }
    moneyTransferCriteria.add(Restrictions.isNull("trial.id"));
    moneyTransferCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
    CategoryCriterion.apply(moneyTransferCriteria, new CategoryCriterion(costType, "costType", MatchMode.EXACT, EmptyPrefixModes.ALL_ROWS));
    return moneyTransferCriteria.list();
}