org.hibernate.criterion.Projection Java Examples

The following examples show how to use org.hibernate.criterion.Projection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
private HashMap<Long, ArrayList<VisitScheduleItem>> listExpandDateModeByProband(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to)
		throws Exception {
	ProjectionList proj = Projections.projectionList();
	proj.add(Projections.id());
	Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, null).values().iterator();
	while (sqlColumnsIt.hasNext()) {
		proj.add(sqlColumnsIt.next());
	}
	visitScheduleItemCriteria.setProjection(proj);
	HashMap<Long, ArrayList<VisitScheduleItem>> result = new HashMap<Long, ArrayList<VisitScheduleItem>>();
	Iterator it = visitScheduleItemCriteria.list().iterator();
	while (it.hasNext()) {
		Object[] row = (Object[]) it.next();
		probandId = (Long) row[4];
		ArrayList<VisitScheduleItem> visitScheduleItems;
		if (result.containsKey(probandId)) {
			visitScheduleItems = result.get(probandId);
		} else {
			visitScheduleItems = new ArrayList<VisitScheduleItem>();
			result.put(probandId, visitScheduleItems);
		}
		visitScheduleItems.add(getVisitScheduleItemFromRow(row));
	}
	CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
	return result;
}
 
Example #2
Source File: DocumentResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Long> getUnassignedDocumentIDsByCrisisID(Long crisisID, Integer count) {
	
	List<Long> docIDList = new ArrayList<Long>();
	Criteria criteria = null;
	try {
		String aliasTable = "taskAssignments";
		String order = "ASC";
		String aliasTableKey = "taskAssignments.id.documentId";
		String[] orderBy = {"valueAsTrainingSample", "documentId"};
		Criterion criterion = Restrictions.conjunction()
				.add(Restrictions.eq("collection.id",crisisID))
				.add(Restrictions.eq("hasHumanLabels",false));

		// get just the documentIDs
		Projection projection = Projections.property("documentId");
		Criterion aliasCriterion =  (Restrictions.isNull(aliasTableKey));
		criteria = createCriteria(criterion, order, orderBy, count, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN);
		docIDList = criteria.list();
		return docIDList;
			
	} catch (Exception e) {
		logger.error("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString(), e);
		throw new HibernateException("getByCriteriaWithAliasByOrder failed, criteria = " + criteria.toString());
	}
}
 
Example #3
Source File: DocumentResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<DocumentDTO> getDocumentForNominalLabelAndCrisis(List<Long> nominalLabelID, Long crisisId) {
	
	List<DocumentDTO> dtoList = new ArrayList<DocumentDTO>();
	
	if (nominalLabelID != null) {
		String aliasTable = "documentNominalLabels";
		String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
		Criteria criteria = null;
		
		try {
			
			Criterion criterion = Restrictions.conjunction()
					.add(Restrictions.eq("collection.id", crisisId))
					.add(Restrictions.eq("hasHumanLabels", true));
			
			Criterion aliasCriterion =  Restrictions.in(aliasTableKeyField, nominalLabelID);
			
			// get just the documentIDs
			Projection projection = Projections.property("documentId");
			
			//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
			criteria = createCriteria(criterion, null, null, null, aliasTable, aliasCriterion, null, JoinType.INNER_JOIN);
			List<Document> docList = criteria.list();
			
			if (docList != null && !docList.isEmpty()) {
				for (Document doc : docList) {
					DocumentDTO dto = new DocumentDTO(doc);
					dtoList.add(dto);
				}
			}
		} catch (Exception e) {
			logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
		}
	}
	
	return dtoList;
}
 
Example #4
Source File: BaseHibernateDao.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: <br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @param detachedCriteria
 * @param pi
 * @param pageSize
 * @param <T> T
 * @return T
 * @throws DaoException <br>
 */
@Override
public <T> PagerList<T> getPageList(final DetachedCriteria detachedCriteria, final int pi, final int pageSize)
    throws DaoException {
    int pageIndex = pi;
    if (pi == 0) {
        pageIndex = 1;
    }

    Criteria criteria = detachedCriteria.getExecutableCriteria(getSession());

    // 查询分页总数
    CriteriaImpl impl = (CriteriaImpl) criteria;
    Projection projection = impl.getProjection();
    Long allCounts = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();

    criteria.setProjection(projection);
    criteria.setFirstResult((pageIndex - 1) * pageSize);
    criteria.setMaxResults(pageSize);

    PagerList<T> resultList = new PagerList<T>();
    resultList.setPageIndex(pageIndex);
    resultList.setPageSize(pageSize);
    if (allCounts == null) {
        allCounts = 0L;
    }
    resultList.setTotalCount(allCounts);

    if (allCounts > 0) {
        resultList.addAll(criteria.list());
    }
    return resultList;
}
 
Example #5
Source File: HibernateUtils.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * find projection from criteria.
 * 
 * @param criteria
 *            Criteria
 * @return Projection
 */
public static Projection findProjection(Criteria criteria) {
    if (criteria instanceof CriteriaImpl) {
        return ((CriteriaImpl) criteria).getProjection();
    } else {
        throw new IllegalArgumentException(criteria
                + " is not a CriteriaImpl");
    }
}
 
Example #6
Source File: GenericBaseCommonDao.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 返回easyui datagrid DataGridReturn模型对象
 */
public DataGridReturn getDataGridReturn(final CriteriaQuery cq,
		final boolean isOffset) {
	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}
	if (StringUtils.isNotBlank(cq.getDataGrid().getSort())) {
		cq.addOrder(cq.getDataGrid().getSort(), cq.getDataGrid().getOrder());
	}

	// 判断是否有排序字段
	if (!cq.getOrdermap().isEmpty()) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
	} else {
		pageSize = allCounts;
	}
	// DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(),
	// cq.getField().split(","), cq.getClass1(), false);
	List list = criteria.list();
	cq.getDataGrid().setResults(list);
	cq.getDataGrid().setTotal(allCounts);
	return new DataGridReturn(allCounts, list);
}
 
Example #7
Source File: GenericBaseCommonDao.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 返回JQUERY datatables DataTableReturn模型对象
 */
public DataTableReturn getDataTableReturn(final CriteriaQuery cq,
		final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
	} else {
		pageSize = allCounts;
	}
	DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(), cq
			.getField().split(","), cq.getEntityClass(), false);
	return new DataTableReturn(allCounts, allCounts, cq.getDataTables()
			.getEcho(), criteria.list());
}
 
Example #8
Source File: GenericBaseCommonDao.java    From jeewx with Apache License 2.0 5 votes vote down vote up
/**
 * 获取分页记录CriteriaQuery 老方法final int allCounts =
 * oConvertUtils.getInt(criteria
 * .setProjection(Projections.rowCount()).uniqueResult(), 0);
 * 
 * @param cq
 * @param isOffset
 * @return
 */
public PageList getPageList(final CriteriaQuery cq, final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	String toolBar = "";
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
		if (cq.getIsUseimage() == 1) {
			toolBar = PagerUtil.getBar(cq.getMyAction(), cq.getMyForm(),
					allCounts, curPageNO, pageSize, cq.getMap());
		} else {
			toolBar = PagerUtil.getBar(cq.getMyAction(), allCounts,
					curPageNO, pageSize, cq.getMap());
		}
	} else {
		pageSize = allCounts;
	}
	return new PageList(criteria.list(), toolBar, offset, curPageNO,
			allCounts);
}
 
Example #9
Source File: HibernatePagingDao.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * 分页查询函数,使用已设好查询条件与排序的<code>Criteria</code>.
 * 
 * @param criteria
 *            条件
 * @param pageNo
 *            当前页号
 * @param pageSize
 *            每页最大记录数
 * @return 含总记录数和当前页数据的Page对象.
 */
@Transactional(readOnly = true)
public Page pagedQuery(Criteria criteria, int pageNo, int pageSize) {
    Assert.notNull(criteria);
    Assert.isTrue(pageNo >= 1, "pageNo should be eg 1");
    Assert.isTrue(criteria instanceof CriteriaImpl);

    // 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
    Projection projection = HibernateUtils.findProjection(criteria);

    List orderEntries = HibernateUtils.findOrderEntries(criteria);
    HibernateUtils.setOrderEntries(criteria, Collections.EMPTY_LIST);

    // 执行查询
    Integer totalCount = this.getCount(criteria);
    // 将之前的Projection和OrderBy条件重新设回去
    criteria.setProjection(projection);

    if (projection == null) {
        criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
    }

    HibernateUtils.setOrderEntries(criteria, orderEntries);

    // 返回分页对象
    if (totalCount < 1) {
        return new Page();
    }

    int start = (pageNo - 1) * pageSize;
    List result = criteria.setFirstResult(start).setMaxResults(pageSize)
            .list();

    Page page = new Page(result, totalCount);
    page.setPageNo(pageNo);
    page.setPageSize(pageSize);

    return page;
}
 
Example #10
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public Criteria createCriteria(Criterion criterion,
		String order, String[] orderBy, Integer count, String aliasTable,
		Criterion aliasCriterion, Projection[] projections, JoinType joinType) {
	
	Session session = getCurrentSession();
	List fetchedList = new ArrayList();
	//logger.info("Entity: " + entityClass + ", current Session = " + session);
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion); 
	criteria.createAlias(aliasTable, aliasTable, joinType).add(aliasCriterion);
	if (orderBy != null) {
		for(int i = 0; i< orderBy.length; i++){
			if (order != null && order.equalsIgnoreCase("desc")) {
				criteria.addOrder(Order.desc(orderBy[i]));
			} else {
				criteria.addOrder(Order.asc(orderBy[i]));
			}
		}
	}
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	
	// set projections
	setProjections(criteria, projections);
	
	return criteria;
	
}
 
Example #11
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
private void setProjections(Criteria criteria, Projection[] projections) {
	ProjectionList projList = Projections.projectionList();
	if(projections != null && projections.length > 0) {
		for(Projection projection : projections) {
			projList.add(projection);
		}
		criteria.setProjection(projList);
	}
	
	
}
 
Example #12
Source File: CriteriaQueryTranslator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName)
		throws HibernateException {

	//first look for a reference to a projection alias
	final Projection projection = rootCriteria.getProjection();
	Type[] projectionTypes = projection == null ?
	                         null :
	                         projection.getTypes( propertyName, subcriteria, this );

	if ( projectionTypes == null ) {
		try {
			//it does not refer to an alias of a projection,
			//look for a property
			return getType( subcriteria, propertyName );
		}
		catch ( HibernateException he ) {
			//not found in inner query , try the outer query
			if ( outerQueryTranslator != null ) {
				return outerQueryTranslator.getType( subcriteria, propertyName );
			}
			else {
				throw he;
			}
		}
	}
	else {
		if ( projectionTypes.length != 1 ) {
			//should never happen, i think
			throw new QueryException( "not a single-length projection: " + propertyName );
		}
		return projectionTypes[0];
	}
}
 
Example #13
Source File: CriteriaQueryTranslator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Get the names of the columns constrained
 * by this criterion.
 */
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 = projection == null ?
	                             null :
	                             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;
	}
}
 
Example #14
Source File: DocumentResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Integer getDocumentCountForNominalLabelAndCrisis(Long nominalLabelID, String crisisCode) {
	if (nominalLabelID != null) {
		String aliasTable = "documentNominalLabels";
		String aliasTableKeyField = "documentNominalLabels.id.nominalLabelId";
		String[] orderBy = {"documentId"};
		Criteria criteria = null;
		
		try {
			CollectionDTO cdto = crisisEJB.getCrisisByCode(crisisCode); 
			
			Criterion criterion = Restrictions.conjunction()
					.add(Restrictions.eq("collection.id",cdto.getCrisisID()))
					.add(Restrictions.eq("hasHumanLabels", true));
			
			Criterion aliasCriterion =  Restrictions.eq(aliasTableKeyField, nominalLabelID);
			
			// get just the documentIDs
			Projection projection = Projections.property("documentId");
			
			//List<Document> docList = this.getByCriteriaWithInnerJoinByOrder(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion);
			criteria = createCriteria(criterion, "DESC", orderBy, null, aliasTable, aliasCriterion, new Projection[] {projection}, JoinType.LEFT_OUTER_JOIN);
			List<Long> docIDList = criteria.list();
			
			if (docIDList != null && !docIDList.isEmpty()) {
				return docIDList.size();
			}
		} catch (Exception e) {
			logger.error("getDocumentCountForNominalLabelAndCrisis failed, criteria = " + criteria.toString(), e);
			return 0;
		}
	}
	return 0;
}
 
Example #15
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Timestamp minStartExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
		org.hibernate.criterion.Criterion or) throws Exception {
	ProjectionList proj = Projections.projectionList();
	LinkedHashMap<String, Projection> sqlColumns = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or);
	proj.add(Projections.sqlProjection(
			"least(min({alias}.start), min(" + ((SQLProjection) sqlColumns.get("tagStart")).getSql() + ")) as minStart",
			new String[] { "minStart" },
			new org.hibernate.type.Type[] { Hibernate.TIMESTAMP }));
	visitScheduleItemCriteria.setProjection(proj);
	return (Timestamp) visitScheduleItemCriteria.uniqueResult();
}
 
Example #16
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Timestamp maxStopExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
		org.hibernate.criterion.Criterion or) throws Exception {
	ProjectionList proj = Projections.projectionList();
	LinkedHashMap<String, Projection> sqlColumns = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or);
	proj.add(Projections.sqlProjection(
			"greatest(max({alias}.stop), max(" + ((SQLProjection) sqlColumns.get("tagStop")).getSql() + "), max(" + ((SQLProjection) sqlColumns.get("durationStop")).getSql()
					+ ")) as maxStop",
			new String[] { "maxStop" },
			new org.hibernate.type.Type[] { Hibernate.TIMESTAMP }));
	visitScheduleItemCriteria.setProjection(proj);
	return (Timestamp) visitScheduleItemCriteria.uniqueResult();
}
 
Example #17
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ArrayList<Object[]> listExpandDateModeProband(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
		SubCriteriaMap criteriaMap, PSFVO psf)
		throws Exception {
	ProjectionList proj = Projections.projectionList();
	proj.add(Projections.id());
	Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, null).values().iterator();
	while (sqlColumnsIt.hasNext()) {
		proj.add(sqlColumnsIt.next());
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	visitScheduleItemCriteria.setProjection(proj);
	ArrayList<Object[]> result = new ArrayList<Object[]>();
	Iterator it = visitScheduleItemCriteria.list().iterator();
	while (it.hasNext()) {
		Object[] row = (Object[]) it.next();
		probandId = (Long) row[4];
		result.add(new Object[] {
				getVisitScheduleItemFromRow(row),
				probandId != null ? this.getProbandDao().load(probandId) : null
		});
	}
	AssociationPath sortFieldAssociationPath = new AssociationPath(psf != null ? psf.getSortField() : null);
	if (sortFieldAssociationPath.isValid()) {
		String sortProperty = sortFieldAssociationPath.getPropertyName();
		if ("start".equals(sortProperty)) {
			Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_START_ASC : VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_START_DESC);
		} else if ("stop".equals(sortProperty)) {
			Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_STOP_ASC : VISIT_SCHEDULE_ITEM_PROBAND_COMPARATOR_STOP_DESC);
		}
	}
	CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
	return result;
}
 
Example #18
Source File: VisitScheduleItemDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private ArrayList<VisitScheduleItem> listExpandDateMode(org.hibernate.Criteria visitScheduleItemCriteria, Long probandId, Timestamp from, Timestamp to,
		org.hibernate.criterion.Criterion or, SubCriteriaMap criteriaMap, PSFVO psf, boolean distinct) throws Exception {
	// projection to avoid multiplebagexception and get calculated dates	
	ProjectionList proj = Projections.projectionList();
	proj.add(Projections.id());
	Iterator<Projection> sqlColumnsIt = applyExpandDateModeCriterions(visitScheduleItemCriteria, probandId, from, to, or).values().iterator();
	while (sqlColumnsIt.hasNext()) {
		proj.add(sqlColumnsIt.next());
	}
	// populate result collection
	CriteriaUtil.applyPSFVO(criteriaMap, psf); //apply filter, populate rowcount
	visitScheduleItemCriteria.setProjection(proj); //set projection for final .list()
	HashSet<Long> dupeCheck = new HashSet<Long>();
	ArrayList<VisitScheduleItem> result = new ArrayList<VisitScheduleItem>();
	Iterator it = visitScheduleItemCriteria.list().iterator();
	while (it.hasNext()) {
		Object[] row = (Object[]) it.next();
		if (!distinct || dupeCheck.add((Long) row[0])) {
			result.add(getVisitScheduleItemFromRow(row));
		}
	}
	// support sorting by start/stop
	AssociationPath sortFieldAssociationPath = new AssociationPath(psf != null ? psf.getSortField() : null);
	if (sortFieldAssociationPath.isValid()) {
		String sortProperty = sortFieldAssociationPath.getPropertyName();
		if ("start".equals(sortProperty)) {
			Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_COMPARATOR_START_ASC : VISIT_SCHEDULE_ITEM_COMPARATOR_START_DESC);
		} else if ("stop".equals(sortProperty)) {
			Collections.sort(result, psf.getSortOrder() ? VISIT_SCHEDULE_ITEM_COMPARATOR_STOP_ASC : VISIT_SCHEDULE_ITEM_COMPARATOR_STOP_DESC);
		}
	}
	// prevent vo caching to substitute unintentionally because of nonunique id's
	CoreUtil.getUserContext().voMapRegisterIgnores(VisitScheduleItem.class);
	return result;
}
 
Example #19
Source File: GenericBaseCommonDao.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 获取分页记录CriteriaQuery 老方法final int allCounts =
 * oConvertUtils.getInt(criteria
 * .setProjection(Projections.rowCount()).uniqueResult(), 0);
 *
 * @param cq
 * @param isOffset
 * @return
 */
public PageList getPageList(final CriteriaQuery cq, final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	String toolBar = "";
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
		if (cq.getIsUseimage() == 1) {
			toolBar = PagerUtil.getBar(cq.getMyAction(), cq.getMyForm(),
					allCounts, curPageNO, pageSize, cq.getMap());
		} else {
			toolBar = PagerUtil.getBar(cq.getMyAction(), allCounts,
					curPageNO, pageSize, cq.getMap());
		}
	} else {
		pageSize = allCounts;
	}
	return new PageList(criteria.list(), toolBar, offset, curPageNO,
			allCounts);
}
 
Example #20
Source File: CriteriaImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Criteria setProjection(Projection projection) {
	CriteriaImpl.this.projection = projection;
	CriteriaImpl.this.projectionCriteria = this;
	setResultTransformer(PROJECTION);
	return this;
}
 
Example #21
Source File: CriteriaImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Criteria setProjection(Projection projection) {
	this.projection = projection;
	this.projectionCriteria = this;
	setResultTransformer( PROJECTION );
	return this;
}
 
Example #22
Source File: GenericBaseCommonDao.java    From jeecg with Apache License 2.0 5 votes vote down vote up
/**
 * 返回JQUERY datatables DataTableReturn模型对象
 */
public DataTableReturn getDataTableReturn(final CriteriaQuery cq,
		final boolean isOffset) {

	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}

	// 判断是否有排序字段
	if (cq.getOrdermap() != null) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
	} else {
		pageSize = allCounts;
	}

	//DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(), cq.getField().split(","), cq.getEntityClass(), false);

	
	return new DataTableReturn(allCounts, allCounts, cq.getDataTables().getEcho(), criteria.list());
}
 
Example #23
Source File: CriteriaQueryTranslator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Type getTypeUsingProjection(Criteria subcriteria, String propertyName)
		throws HibernateException {

	//first look for a reference to a projection alias
	final Projection projection = rootCriteria.getProjection();
	Type[] projectionTypes = projection == null ?
			null :
			projection.getTypes( propertyName, subcriteria, this );

	if ( projectionTypes == null ) {
		try {
			//it does not refer to an alias of a projection,
			//look for a property
			return getType( subcriteria, propertyName );
		}
		catch ( HibernateException he ) {
			//not found in inner query , try the outer query
			if ( outerQueryTranslator != null ) {
				return outerQueryTranslator.getType( subcriteria, propertyName );
			}
			else {
				throw he;
			}
		}
	}
	else {
		if ( projectionTypes.length != 1 ) {
			//should never happen, i think
			throw new QueryException( "not a single-length projection: " + propertyName );
		}
		return projectionTypes[0];
	}
}
 
Example #24
Source File: CriteriaQueryTranslator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
	}
}
 
Example #25
Source File: GenericBaseCommonDao.java    From jeecg with Apache License 2.0 4 votes vote down vote up
/**
	 * 返回easyui datagrid DataGridReturn模型对象
	 */

	public void getDataGridReturn(CriteriaQuery cq,final boolean isOffset) {

		Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(getSession());
		CriteriaImpl impl = (CriteriaImpl) criteria;
		// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
		Projection projection = impl.getProjection();

//		final int allCounts = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
		Object allCountsObj = criteria.setProjection(Projections.rowCount()).uniqueResult();
		final int allCounts;
		if(allCountsObj==null){
			allCounts = 0;
		}else{
			allCounts = ((Long) allCountsObj).intValue();
		}

		criteria.setProjection(projection);
		if (projection == null) {
			criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}

		Map<String, Object> ordermap = cq.getOrdermap();
		if(ordermap==null){
			ordermap = new LinkedHashMap<String, Object>();
		}
		
		String sort = cq.getDataGrid().getSort();
		if (StringUtils.isNotBlank(sort)) {
			String []sortArr = sort.split(",");
			String []orderArr = cq.getDataGrid().getOrder().split(",");
			if(sortArr.length != orderArr.length && orderArr.length > 0){
				for (int i = 0; i < sortArr.length; i++) {
					if(SortDirection.asc.equals(SortDirection.toEnum(orderArr[0]))){
						ordermap.put(sortArr[i], SortDirection.asc);
					}else{
						ordermap.put(sortArr[i], SortDirection.desc);
					}
				}
			}else if(sortArr.length == orderArr.length){
				for (int i = 0; i < sortArr.length; i++) {
					if(SortDirection.asc.equals(SortDirection.toEnum(orderArr[i]))){
						ordermap.put(sortArr[i], SortDirection.asc);
					}else{
						ordermap.put(sortArr[i], SortDirection.desc);
					}
				}
			}
		}
		if(!ordermap.isEmpty() && ordermap.size()>0){
			cq.setOrder(ordermap);
		}


		// 判断是否有排序字段
//		if (!cq.getOrdermap().isEmpty()) {
//			cq.setOrder(cq.getOrdermap());
//		}
		int pageSize = cq.getPageSize();// 每页显示数
		int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),pageSize);// 当前页
		int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
		if (isOffset) {// 是否分页
			criteria.setFirstResult(offset);
			criteria.setMaxResults(cq.getPageSize());
		} else {
			pageSize = allCounts;
		}
		// DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(),
		// cq.getField().split(","), cq.getClass1(), false);
		List<?> list = criteria.list();
		cq.getDataGrid().setResults(list);
		cq.getDataGrid().setTotal(allCounts);

		cq.clear();
		cq = null;

		//return new DataGridReturn(allCounts, list);

	}
 
Example #26
Source File: CoreDBServiceFacade.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
public Criteria createCriteria(Criterion criterion,
String order, String[] orderBy, Integer count, String aliasTable,
Criterion aliasCriterion, Projection[] projections, JoinType joinType);
 
Example #27
Source File: EntityCriteria.java    From onedev with MIT License 4 votes vote down vote up
public EntityCriteria<T> setProjection(Projection projection) {
	criteria.setProjection(projection);
	return this;
}
 
Example #28
Source File: DetachedCriteriaUtil.java    From jeewx with Apache License 2.0 4 votes vote down vote up
/**
 * 该方法提供DetachedCriteria对查询字段的封装, 2008-9-29
 * 2009.9.9修改后,可支持无限级联取部分字段,如取如下字段 
 * user.organization.parentOrganization.parentOrganization.orgName
 * 但请注意1点 ,连接采用内联,级联越多,结果集可能就越少;
 * @author
 * @param columnNames
 *            字符串数组,以数据的形式接收要查询的字段属性,如String[] column={"属性1","属性2","属性3"};
 * @param pojoClass
 *            实体类的Class,如Mobile.class;
 * @param aials
 *            为要查询的POJO对象指定一个别名
 * @return DetachedCriteria 的一个对象,如果需要查询条件,在些对象后追加查询条件。
 * 
 * @param forJoinTable 是否多表连接查询
 */
public static void selectColumn(DetachedCriteria criteria, String[] columnNames,
		Class<?> pojoClass,boolean forJoinTable) {
	if (null == columnNames) {
		return;
	}

	//使用这个临时变量集合,是因为dinstinct关键字要放在最前面,而distinct关键字要在下面才决定放不放,
	List<Projection> tempProjectionList = new ArrayList<Projection>();
	
	Set<String> aliases = getAliasesFromRequest();
	boolean hasJoniTable = false;
	String rootAlias = criteria.getAlias();
	for (String property : columnNames) {
		if(property.contains("_")){
			String[] propertyChain = property.split("_");
			createAlias(criteria,rootAlias,aliases,propertyChain,0);
			tempProjectionList.add(Projections.property(StringUtil.getProperty(property)).as(StringUtil.getProperty(property)));
			hasJoniTable = true;
		}else{
			tempProjectionList.add(Projections.property(rootAlias + POINT + property).as(property));
		}
	}
	
	 projectionList = Projections.projectionList();
	if(hasJoniTable || forJoinTable ||  getHasJoinTatleFromRequest()){//这个一定要放在tempProjectionList的前面,因为distinct要在最前面
		projectionList.add(Projections.distinct(Projections.id()));
	}
	
	for (Projection proj : tempProjectionList) {
		projectionList.add(proj);
	}
	
	criteria.setProjection(projectionList);
	
	
	if(!hasJoniTable){
		criteria.setResultTransformer(Transformers.aliasToBean(pojoClass));
	}else{//下面这个是自定义的结果转换器
		criteria.setResultTransformer(new AliasToBean(pojoClass));
	}
}
 
Example #29
Source File: CriteriaImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Criteria setProjection(Projection projection) {
	CriteriaImpl.this.projection = projection;
	CriteriaImpl.this.projectionCriteria = this;
	setResultTransformer(PROJECTION);
	return this;
}
 
Example #30
Source File: CriteriaImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public Criteria setProjection(Projection projection) {
	this.projection = projection;
	this.projectionCriteria = this;
	setResultTransformer( PROJECTION );
	return this;
}