Java Code Examples for org.hibernate.Criteria#setResultTransformer()

The following examples show how to use org.hibernate.Criteria#setResultTransformer() . These examples are extracted from open source projects. 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 Project: chipster   File: StatDataSource.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private Map getJobDateRange(Session session, boolean ignoreTestAccounts) {
	//Get min and max values of dates
	Criteria rangeCriteria = session.createCriteria(JobLogEntry.class);
	testAccountFilter.addCriteriaForTestAccounts(session, ignoreTestAccounts, rangeCriteria);
	ProjectionList projections = Projections.projectionList();
	projections.add(Projections.min(JobLogContainer.START_TIME), "min");
	projections.add(Projections.max(JobLogContainer.START_TIME), "max");
	rangeCriteria.setProjection(projections);
	rangeCriteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

	@SuppressWarnings("unchecked")
	List<Map> rangeList = rangeCriteria.list();

	return rangeList.get(0);
}
 
Example 2
@SuppressWarnings("unchecked")
public List<Mpp> getMedecinePackagesFromIngredients(String searchString, String lang, List<String> types, int first, int count) {
    log.debug("Getting medecine packages from ingredients for " + searchString + " from " + first + ", count=" + count);
    Session sess = this.getSessionFactory().getCurrentSession();
    Criteria c = sess.createCriteria(Mpp.class);
    addLangRestriction(c, lang);
    addTypesRestriction(c, types);

    c.createAlias("compositions", "comp").createAlias("comp.ingredient", "ingrd");
    c.add(Restrictions.or(Restrictions.ilike("name", searchString, MatchMode.START),
            Restrictions.ilike("ingrd.name", searchString, MatchMode.START)));

    c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    c.setFirstResult(first);
    c.setMaxResults(count);
    c.addOrder(Order.asc("name"));
    List<Mpp> result = c.list();
    return result;
}
 
Example 3
Source Project: sailfish-core   File: HibernateStorage.java    License: Apache License 2.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getAllEntities(Class<T> entityClass) {
	
	Session session = null;
	
	try {
           session = sessionFactory.openSession();
		
		Criteria criteria = session.createCriteria(entityClass);
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		
		return criteria.list();
		
	} finally {
           if(session != null) {
               session.close();
           }
	}
	
}
 
Example 4
/**
 * Bounds are calculated locally, can use any filter, but slower than native.
 * 
 * @param filter
 *            filter which needs to be applied
 * @return the bounds of the specified features
 * @throws LayerException
 *             oops
 */
private Envelope getBoundsLocal(Filter filter) throws LayerException {
	try {
		Session session = getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());
		CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);
		Criterion c = (Criterion) filter.accept(visitor, criteria);
		if (c != null) {
			criteria.add(c);
		}
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<?> features = criteria.list();
		Envelope bounds = new Envelope();
		for (Object f : features) {
			Envelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();
			if (!geomBounds.isNull()) {
				bounds.expandToInclude(geomBounds);
			}
		}
		return bounds;
	} catch (HibernateException he) {
		throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()
				.getDataSourceName(), filter.toString());
	}
}
 
Example 5
Source Project: auction-website   File: BidService.java    License: MIT License 6 votes vote down vote up
/**
 * @param uid userId
 * @return a list of auction-ids that user with uid has bided
 */
public List getAllUserBids(long uid) {
    Session session = HibernateUtil.getSession();
    List bids = null;
    try {
        Criteria criteria = session.createCriteria( BidEntity.class );
        criteria.add(Restrictions.eq("bidderId", uid));
        criteria.setProjection( Projections.distinct( Projections.property( "auctionId" ) ));
        criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
        bids = criteria.list();
    } catch (HibernateException e) {
        e.printStackTrace();
    } finally {
        try { if (session != null) session.close(); } catch (Exception ignored) {}
    }
    return bids;
}
 
Example 6
/**
 * Lookup a list of all KickstartData objects located on the Satellite
 *  Should not be used by much.  Ignores org!
 * @return List of KickstartData objects if found
 */
public static List<KickstartData> listAllKickstartData() {
    Session session = getSession();
    Criteria c = session.createCriteria(KickstartData.class);
    // Hibernate does not filter out duplicate references by default
    c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return c.list();
}
 
Example 7
Source Project: jdal   File: HibernateDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get Page, apply filter if any.
 * If Filter is a entity model, use Example to create a criteria.
 * else enable filter by name on session. 
 * @param page with page definitions
 * @return page of results
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public <K> Page<K> getPage(Page<K> page) {
	
	List data = null;
	// try named query
	Query query = getQuery(page);
	if (query != null) {
		data = query.list();
	}
	else {
		// try filter, example and criteria builders
		Criteria criteria = getCriteria(page);
		ResultTransformer rt = ((CriteriaImpl) criteria).getResultTransformer(); 
		criteria.setProjection(Projections.rowCount());
		 page.setCount(((Long) criteria.uniqueResult()).intValue());
		// reset criteria
		criteria.setProjection(null);
		criteria.setResultTransformer(rt);
		// set start index and page size
		criteria.setFirstResult(page.getStartIndex())
			.setMaxResults(page.getPageSize());
		applyOrder(page, criteria);
		// run it
		criteria.setCacheable(cachePageQueries);
		data = criteria.list();
	}
	
	page.setData(data);
	
	return page;
}
 
Example 8
Source Project: sailfish-core   File: HibernateStorage.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> List<T> getAllEntities(Class<T> entityClass, List<Criterion> criterions, String orderField, boolean orderAsc) {
	
	Session session = null;
	
	try {
           session = sessionFactory.openSession();
		
		Criteria criteria = session.createCriteria(entityClass);
		
		for (Criterion criterion : criterions) {
			criteria.add(criterion);
		}

           criteria.addOrder(orderAsc ? Order.asc(orderField) : Order.desc(orderField));
           criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		
		return criteria.list();
		
	} finally {
           if(session != null) {
               session.close();
           }
	}
	
}
 
Example 9
Source Project: lemon   File: HibernatePagingDao.java    License: 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 Project: jeewx   File: GenericBaseCommonDao.java    License: 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 11
@Override
   public Long getUsersCount(String query) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(UserAccount.class);
       criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

       if (StringUtils.hasText(query)){
           String wildcard ='%'+ URLDecoder.decode(query.trim())+'%';
           criteria.add(Restrictions.ilike("userName", wildcard));
       }

       ScrollableResults scroll = criteria.scroll();
       int i = scroll.last() ? scroll.getRowNumber() + 1 : 0;
       return Long.valueOf(i);
}
 
Example 12
Source Project: jeewx   File: GenericBaseCommonDao.java    License: 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 13
Source Project: primefaces-blueprints   File: DAOService.java    License: The Unlicense 5 votes vote down vote up
public Customer validateUser(String username, String password) {
    org.hibernate.Transaction tx = getSession().beginTransaction();
    Criteria criteria = getSession().createCriteria(Customer.class);
    criteria.add(Restrictions.eq("email", username));
    criteria.add(Restrictions.eq("password", password));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    Customer user = (Customer) criteria.uniqueResult();
    tx.commit();
    getSession().close();
    _log.info("Listed Successfully....");
    return user;
}
 
Example 14
Source Project: olat   File: GenericDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Map<String, Object> restrictionNameValues) {
    Criteria criteria = getCurrentSession().createCriteria(type);
    Iterator<String> keys = restrictionNameValues.keySet().iterator();
    while (keys.hasNext()) {
        String restrictionName = keys.next();
        Object restrictionValue = restrictionNameValues.get(restrictionName);
        criteria = criteria.add(Restrictions.eq(restrictionName, restrictionValue));
    }
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return criteria.list();
}
 
Example 15
Source Project: primefaces-blueprints   File: DAOService.java    License: The Unlicense 5 votes vote down vote up
public User validateUser(String username, String password) {
    org.hibernate.Transaction tx = getSession().beginTransaction();
    Criteria criteria = getSession().createCriteria(User.class);
    criteria.add(Restrictions.eq("username", username));
    criteria.add(Restrictions.eq("password", password));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    User user = (User) criteria.uniqueResult();
    tx.commit();
    getSession().close();
    _log.info("Listed Successfully....");
    return user;
}
 
Example 16
Source Project: primefaces-blueprints   File: DAOService.java    License: The Unlicense 5 votes vote down vote up
public Profile validateUser(String username, String password) {
    org.hibernate.Transaction tx = getSession().beginTransaction();
    Criteria criteria = getSession().createCriteria(Profile.class);
    criteria.add(Restrictions.eq("email", username));
    criteria.add(Restrictions.eq("password", password));
    criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    Profile user = (Profile) criteria.uniqueResult();
    tx.commit();
    getSession().close();
    _log.info("Listed Successfully....");
    return user;
}
 
Example 17
@Override
public Criteria distinct(Criteria criteria) {
	criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
	return criteria;
}
 
Example 18
@SuppressWarnings("unchecked")
@Override
public List<Collection> getStoppedCollections(Integer start, Integer limit, String terms, String sortColumn, String sortDirection) {
	Criteria criteriaIds = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteriaIds.setProjection(Projections.projectionList()
			.add(Projections.property("id"), "id"));

	LogicalExpression or = Restrictions.or(
			Restrictions.eq("status", CollectionStatus.STOPPED),
			Restrictions.eq("status", CollectionStatus.NOT_RUNNING)
			);
	
	LogicalExpression orAll = Restrictions.or(
			or,
			Restrictions.eq("status", CollectionStatus.FATAL_ERROR)
			);
	
	criteriaIds.add(orAll);
	addCollectionSearchCriteria(terms, criteriaIds);
	searchCollectionsAddOrder(sortColumn, sortDirection, criteriaIds);

	if (start != null) {
		criteriaIds.setFirstResult(start);
	}
	if (limit != null) {
		criteriaIds.setMaxResults(limit);
	}

	List<Integer> ids = criteriaIds.list();

	if (ids.size() == 0){
		return Collections.emptyList();
	}

	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);

	criteria.add(Restrictions.in("id", ids));
	searchCollectionsAddOrder(sortColumn, sortDirection, criteria);

	return criteria.list();
}
 
Example 19
Source Project: olat   File: GenericDaoImpl.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public List<T> findAll() {
    Criteria criteria = getCurrentSession().createCriteria(type);
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return criteria.list();
}
 
Example 20
Source Project: jeecg   File: GenericBaseCommonDao.java    License: 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);

	}