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

The following examples show how to use org.hibernate.Criteria#setResultTransformer() . 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: DrugsDAOImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 2
Source File: StatDataSource.java    From chipster with 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 3
Source File: HibernateStorage.java    From sailfish-core with 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
Source File: HibernateLayer.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 File: BidService.java    From auction-website with 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
Source File: DAOService.java    From primefaces-blueprints with 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 7
Source File: DAOService.java    From primefaces-blueprints with 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 8
Source File: GenericDaoImpl.java    From olat with 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 9
Source File: DAOService.java    From primefaces-blueprints with 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 10
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 11
Source File: UserAccountRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 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 13
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 14
Source File: HibernateStorage.java    From sailfish-core with 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 15
Source File: HibernateDao.java    From jdal with 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 16
Source File: KickstartFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 17
Source File: SimpleHibernateDao.java    From DWSurvey with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Criteria distinct(Criteria criteria) {
	criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
	return criteria;
}
 
Example 18
Source File: CollectionRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
@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 File: GenericDaoImpl.java    From olat with 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 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);

	}