org.hibernate.criterion.Order Java Examples

The following examples show how to use org.hibernate.criterion.Order. 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: ECRFFieldDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected Collection<String> handleFindSections(Long trialId, Long ecrfId, String sectionPrefix, Integer limit) throws Exception {
	org.hibernate.Criteria ecrfFieldCriteria = createEcrfFieldCriteria();
	if (trialId != null) {
		ecrfFieldCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (ecrfId != null) {
		ecrfFieldCriteria.add(Restrictions.eq("ecrf.id", ecrfId.longValue()));
	}
	CategoryCriterion.apply(ecrfFieldCriteria, new CategoryCriterion(sectionPrefix, "section", MatchMode.START));
	ecrfFieldCriteria.addOrder(Order.asc("section"));
	ecrfFieldCriteria.setProjection(Projections.distinct(Projections.property("section")));
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.ECRF_FIELD_SECTION_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.ECRF_FIELD_SECTION_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), ecrfFieldCriteria);
	return ecrfFieldCriteria.list();
}
 
Example #2
Source File: SignatureDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
protected Signature handleFindRecentSignature(SignatureModule module, Long id) {
	org.hibernate.Criteria signatureCriteria = this.getSession().createCriteria(Signature.class);
	if (module != null) {
		signatureCriteria.add(Restrictions.eq("module", module));
		if (id != null) {
			switch (module) {
				case TRIAL_SIGNATURE:
					signatureCriteria.add(Restrictions.eq("trial.id", id.longValue()));
					break;
				case ECRF_SIGNATURE:
					signatureCriteria.add(Restrictions.eq("ecrfStatusEntry.id", id.longValue()));
					break;
				default:
			}
		}
	}
	signatureCriteria.addOrder(Order.desc("id"));
	signatureCriteria.setMaxResults(1);
	return (Signature) signatureCriteria.uniqueResult();
}
 
Example #3
Source File: CountersDaoImpl.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Get all the Counters information from DB
 */
@SuppressWarnings("unchecked")
private List<Counters> getAllCounters() {
    Session session = sessionFactory.openSession();
    Criteria counterCriteria = session.createCriteria(CounterEntity.class, "counter");
    counterCriteria.addOrder(Order.asc("counter.position"));
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.property("counter.counterId"));
    projectionList.add(Projections.property("counter.counterName"));
    projectionList.add(Projections.property("counter.position"));
    projectionList.add(Projections.property("counter.delInd"));

    counterCriteria.setProjection(projectionList);
    List<Counters> counterList = new ArrayList<Counters>();
    for (Object[] counterObj : (List<Object[]>) counterCriteria.list()) {
        Counters counter = new Counters();
        counter.setCounterId(Integer.parseInt(String.valueOf(counterObj[0])));
        counter.setCounterName(String.valueOf(counterObj[1]));
        counter.setPosition(Integer.parseInt(String.valueOf(counterObj[2])));
        counter.setDelInd(Integer.parseInt(String.valueOf(counterObj[3])));
        counterList.add(counter);
    }
    session.close();
    return counterList;
}
 
Example #4
Source File: ProbandListStatusEntryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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();
}
 
Example #5
Source File: HibernateBasicDao.java    From lemon with Apache License 2.0 6 votes vote down vote up
/**
 * 获得所有记录,带排序参数.
 * 
 * @param <T>
 *            实体类型
 * @param entityClass
 *            实体类型
 * @param orderBy
 *            排序字段名
 * @param isAsc
 *            是否正序排列
 * @return 返回结果列表
 */
@Transactional(readOnly = true)
public <T> List<T> getAll(Class<T> entityClass, String orderBy,
        boolean isAsc) {
    if (StringUtils.hasText(orderBy)) {
        Criteria criteria = this.getSession().createCriteria(entityClass);

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

        return criteria.list();
    } else {
        return this.getAll(entityClass);
    }
}
 
Example #6
Source File: DrugsDAOImpl.java    From icure-backend with GNU General Public License v2.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 = 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 #7
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public List<String> getAllLocations(String siteId) throws DataAccessException {
			DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setProjection(Projections.distinct(Projections.projectionList()
				    	    .add(Projections.property("location"), "location") )).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY)				
			.addOrder(Order.asc("location")).createCriteria("signupSites")
			.add(Restrictions.eq("siteId", siteId));
	
	List<String> locations = (List<String>) getHibernateTemplate().findByCriteria(criteria);
	
	if(locations !=null && !locations.isEmpty()){
		return locations;
	}
	
	return null;
}
 
Example #8
Source File: Kost1Dao.java    From projectforge-webapp with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public List<Kost1DO> getList(final BaseSearchFilter filter)
{
  final KostFilter myFilter;
  if (filter instanceof KostFilter) {
    myFilter = (KostFilter) filter;
  } else {
    myFilter = new KostFilter(filter);
  }
  final QueryFilter queryFilter = new QueryFilter(myFilter);
  if (myFilter.isActive() == true) {
    queryFilter.add(Restrictions.eq("kostentraegerStatus", KostentraegerStatus.ACTIVE));
  } else if (myFilter.isNonActive() == true) {
    queryFilter.add(Restrictions.eq("kostentraegerStatus", KostentraegerStatus.NONACTIVE));
  } else if (myFilter.isEnded() == true) {
    queryFilter.add(Restrictions.eq("kostentraegerStatus", KostentraegerStatus.ENDED));
  } else if (myFilter.isNotEnded() == true) {
    queryFilter.add(Restrictions.or(Restrictions.ne("kostentraegerStatus", ProjektStatus.ENDED), Restrictions.isNull("kostentraegerStatus")));
  }
  queryFilter.addOrder(Order.asc("nummernkreis")).addOrder(Order.asc("bereich")).addOrder(Order.asc("teilbereich")).addOrder(Order.asc("endziffer"));
  return getList(queryFilter);
}
 
Example #9
Source File: HistoryProcessVariableQueryImpl.java    From uflo with Apache License 2.0 6 votes vote down vote up
private void buildCriteria(Criteria criteria,boolean queryCount){
	if(!queryCount && firstResult>0){
		criteria.setFirstResult(firstResult);			
	}
	if(!queryCount && maxResults>0){
		criteria.setMaxResults(maxResults);			
	}
	if(historyProcessInstanceId>0){
		criteria.add(Restrictions.eq("historyProcessInstanceId",historyProcessInstanceId));
	}
	if(StringUtils.isNotEmpty(key)){
		criteria.add(Restrictions.eq("key", key));
	}
	
	if(!queryCount){
		for(String ascProperty:ascOrders){
			criteria.addOrder(Order.asc(ascProperty));
		}
		for(String descProperty:descOrders){
			criteria.addOrder(Order.desc(descProperty));
		}
	}
}
 
Example #10
Source File: KpiDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<RuleOutput> listRuleOutputByType(final String type, final STATUS status) {
    List<SbiKpiRuleOutput> sbiRuleOutputs = list(new ICriterion<SbiKpiRuleOutput>() {
        @Override
        public Criteria evaluate(Session session) {
            // Ordering by rule name and measure name
            Criteria c = session.createCriteria(SbiKpiRuleOutput.class).createAlias("type", "type").createAlias("sbiKpiAlias", "sbiKpiAlias")
                    .createAlias("sbiKpiRule", "sbiKpiRule").add(Restrictions.eq("type.valueCd", type)).addOrder(Order.asc("sbiKpiRule.name"))
                    .addOrder(Order.asc("sbiKpiAlias.name"));
            switch (status) {
                case ACTIVE:
                    c.add(Restrictions.eq("sbiKpiRule.active", 'T'));
                    break;
                case NOT_ACTIVE:
                    c.add(Restrictions.ne("sbiKpiRule.active", 'T'));
                    break;
                case ALL:
                    // No restrictions
                    break;
            }
            return c;
        }
    });

    List<RuleOutput> ruleOutputs = new ArrayList<>();
    for (SbiKpiRuleOutput sbiKpiRuleOutput : sbiRuleOutputs) {
        ruleOutputs.add(from(sbiKpiRuleOutput));

    }
    return ruleOutputs;
}
 
Example #11
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public List<SignupMeeting> getSignupMeetings(String siteId, Date startDate,
		Date endDate) {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY)
			.add(Restrictions.ge("endTime", startDate))
			.add(Restrictions.lt("startTime", endDate))
			.addOrder(Order.asc("startTime")).createCriteria("signupSites")
			.add(Restrictions.eq("siteId", siteId));

	return (List<SignupMeeting>) getHibernateTemplate().findByCriteria(criteria);
}
 
Example #12
Source File: MessageBundleServiceImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
@Transactional(readOnly = true)
public List<String> getAllBaseNames() {
    Criteria query = sessionFactory.getCurrentSession().createCriteria(MessageBundleProperty.class)
            .setProjection(Projections.distinct(Projections.property("baseName")))
            .addOrder(Order.asc("baseName"));
    List<String> results = (List<String>) query.list();
    return results;

}
 
Example #13
Source File: SimpleHibernateDao.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<T> getAll(String orderByProperty, boolean isAsc) {
	Criteria c = createCriteria();
	if (isAsc) {
		c.addOrder(Order.asc(orderByProperty));
	} else {
		c.addOrder(Order.desc(orderByProperty));
	}
	return c.list();
}
 
Example #14
Source File: StatsUpdateManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Date getEventDateFromLatestJobRun() throws Exception {
	Date r = getHibernateTemplate().execute(session -> {
           Criteria c = session.createCriteria(JobRunImpl.class);
           c.add(Expression.isNotNull("lastEventDate"));
           c.setMaxResults(1);
           c.addOrder(Order.desc("id"));
           List jobs = c.list();
           if(jobs != null && jobs.size() > 0){
               JobRun jobRun = (JobRun) jobs.get(0);
               return jobRun.getLastEventDate();
           }
           return null;
       });
	return r;
}
 
Example #15
Source File: SiteDAOImpl.java    From webcurator with Apache License 2.0 5 votes vote down vote up
/**
 * Find permissions by Site
 * @param anAgencyOid The OID of the agency to restrict the search to.
 * @param aSiteTitle The title of the site.
 * @param aPageNumber The page number to return.
 * @return A List of Permissions.
 */
public Pagination findPermissionsBySiteTitle(final Long anAgencyOid, final String aSiteTitle, final int aPageNumber) {
	return (Pagination) getHibernateTemplate().execute(
			new HibernateCallback() {
				public Object doInHibernate(Session session) {
					
					Criteria query = session.createCriteria(Permission.class);
					query.add(Restrictions.disjunction()
						 .add(Restrictions.isNull("endDate"))
						 .add(Restrictions.ge("endDate", new Date())));
				
					query.createCriteria("owningAgency")
						 .add(Restrictions.eq("oid", anAgencyOid));

					query.createCriteria("site")
						 .add(Restrictions.ilike("title", aSiteTitle, MatchMode.START))
						 .add(Restrictions.eq("active", true))
						 .addOrder(Order.asc("title"));
					
					Criteria cntQuery = session.createCriteria(Permission.class);
					cntQuery.add(Restrictions.disjunction()
						 .add(Restrictions.isNull("endDate"))
						 .add(Restrictions.ge("endDate", new Date())));
				
					cntQuery.createCriteria("owningAgency")
						 .add(Restrictions.eq("oid", anAgencyOid));

					cntQuery.createCriteria("site")
						 .add(Restrictions.ilike("title", aSiteTitle, MatchMode.START))
						 .add(Restrictions.eq("active", true));	

					cntQuery.setProjection(Projections.rowCount());
					
					return new Pagination(cntQuery, query, aPageNumber, Constants.GBL_PAGE_SIZE);
				}
			}
		);			
}
 
Example #16
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@SuppressWarnings("unchecked")
public List<SignupMeeting> getAllSignupMeetings(String siteId) {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).addOrder(Order.asc("startTime"))
			.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
			.createCriteria("signupSites").add(
					Restrictions.eq("siteId", siteId));
	return (List<SignupMeeting>) getHibernateTemplate().findByCriteria(criteria);
}
 
Example #17
Source File: AspDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<Asp> handleFindAsps(String nameInfix, Integer limit) throws Exception {
	org.hibernate.Criteria aspCriteria = createAspCriteria(true);
	applyAspNameCriterions(aspCriteria, nameInfix);
	aspCriteria.addOrder(Order.asc("name"));
	CriteriaUtil.applyLimit(limit,
			Settings.getIntNullable(SettingCodes.ASP_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.ASP_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT),
			aspCriteria);
	if (MATCH_SUBSTANCE_NAME || MATCH_ATC_CODE_CODE) {
		return CriteriaUtil.listDistinctRoot(aspCriteria, this, "name");
	} else {
		return aspCriteria.list();
	}
}
 
Example #18
Source File: TrainingRecordSectionDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<TrainingRecordSection> handleFindByVisibleIdSorted(Boolean visible, Long sectionId) throws Exception {
	org.hibernate.Criteria trainingRecordSectionCriteria = this.getSession().createCriteria(TrainingRecordSection.class);
	trainingRecordSectionCriteria.setCacheable(true);
	CriteriaUtil.applyVisibleIdCriterion("visible", trainingRecordSectionCriteria, visible, sectionId);
	trainingRecordSectionCriteria.addOrder(Order.asc("position"));
	return trainingRecordSectionCriteria.list();
}
 
Example #19
Source File: InventoryBookingDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<InventoryBooking> handleFindByAppointmentDepartmentsCalendarInterval(Long probandDepartmentId, Long courseDepartmentId, Long trialDepartmentId,
		String calendar, Timestamp from, Timestamp to,
		Boolean isProbandAppointment, Boolean isRelevantForProbandAppointments,
		Boolean isCourseAppointment, Boolean isRelevantForCourseAppointments,
		Boolean isTrialAppointment, Boolean isRelevantForTrialAppointments) throws Exception {
	Criteria bookingCriteria = createBookingCriteria();
	CriteriaUtil.applyClosedIntervalCriterion(bookingCriteria, from, to, null);
	if (probandDepartmentId != null) {
		bookingCriteria.createCriteria("proband", CriteriaSpecification.LEFT_JOIN).add(
				Restrictions.or(Restrictions.isNull("department.id"), Restrictions.eq("department.id", probandDepartmentId.longValue())));
	}
	if (courseDepartmentId != null) {
		bookingCriteria.createCriteria("course", CriteriaSpecification.LEFT_JOIN).add(
				Restrictions.or(Restrictions.isNull("department.id"), Restrictions.eq("department.id", courseDepartmentId.longValue())));
	}
	if (trialDepartmentId != null) {
		bookingCriteria.createCriteria("trial", CriteriaSpecification.LEFT_JOIN).add(
				Restrictions.or(Restrictions.isNull("department.id"), Restrictions.eq("department.id", trialDepartmentId.longValue())));
	}
	applyIncludeAppointmentsCriterion(bookingCriteria, isProbandAppointment, "proband.id", isRelevantForProbandAppointments, "relevantForProbandAppointments");
	applyIncludeAppointmentsCriterion(bookingCriteria, isCourseAppointment, "course.id", isRelevantForCourseAppointments, "relevantForCourseAppointments");
	applyIncludeAppointmentsCriterion(bookingCriteria, isTrialAppointment, "trial.id", isRelevantForTrialAppointments, "relevantForTrialAppointments");
	CategoryCriterion.apply(bookingCriteria, new CategoryCriterion(calendar, "calendar", MatchMode.EXACT, EmptyPrefixModes.ALL_ROWS));
	bookingCriteria.addOrder(Order.asc("start"));
	return bookingCriteria.list();
}
 
Example #20
Source File: BasicHibernateDao.java    From base-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 获取全部对象
 *
 * @param orders 排序对象,不需要排序,可以不传
 * 
 * @return List
 */
public List<T> getAll(Order ...orders) {
	Criteria c = createCriteria();
	if(ArrayUtils.isNotEmpty(orders)) {
		setOrderToCriteria(c, orders);
	}
	return c.list();
}
 
Example #21
Source File: OpsSystCategoryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<String> handleFindCategoryPreferredRubricLabels(
		String preferredRubricLabelInfix, Integer limit) throws Exception {
	org.hibernate.Criteria opsSystCategoryCriteria = this.getSession().createCriteria(OpsSystCategory.class);
	opsSystCategoryCriteria.setCacheable(true);
	CategoryCriterion.apply(opsSystCategoryCriteria, new CategoryCriterion(preferredRubricLabelInfix, "preferredRubricLabel", MatchMode.ANYWHERE));
	opsSystCategoryCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("preferredRubricLabel", ""), Restrictions.isNull("preferredRubricLabel"))));
	opsSystCategoryCriteria.addOrder(Order.asc("preferredRubricLabel"));
	opsSystCategoryCriteria.setProjection(Projections.distinct(Projections.property("preferredRubricLabel")));
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.OPS_SYST_CATEGORY_PREFERRED_RUBRIC_LABEL_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.OPS_SYST_CATEGORY_PREFERRED_RUBRIC_LABEL_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), opsSystCategoryCriteria);
	return opsSystCategoryCriteria.list();
}
 
Example #22
Source File: UserDaoImpl.java    From sdudoc with MIT License 5 votes vote down vote up
@Override
public Pager<User> listUserByPage(int pageNo, int pageSize) {
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(User.class);
	long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	criteria.setProjection(null);
	criteria.addOrder(Order.desc("registerDate"));
	criteria.setFirstResult((pageNo - 1) * pageSize);
	criteria.setMaxResults(pageSize);
	List<User> results = criteria.list();
	return new Pager<User>(pageSize, pageNo, recordTotal, results);
}
 
Example #23
Source File: TriggerEventManagerHibernateImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * Internal search for events. Applies the sort and optionally the limit/offset.
 */
protected List<TriggerEvent> getTriggerEvents(Date after, Date before, List<String> jobs, String triggerName, TriggerEvent.TRIGGER_EVENT_TYPE[] types, Integer first, Integer size) {
    final Criteria criteria = buildCriteria(after, before, jobs, triggerName, types);
    // We put the newest items first as generally that's what people are most interested in.
    criteria.addOrder(Order.desc("time"));
    // Sort by event type so that if the time of 2 events is the same the fired event happens before
    // the completed event.
    criteria.addOrder(Order.asc("eventType"));
    if (first != null && size != null)
    {
        criteria.setFirstResult(first).setMaxResults(size);
    }
    return criteria.list();
}
 
Example #24
Source File: ProbandDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Proband handleFindByMaxAlias(boolean person, String aliasPattern) throws Exception {
	org.hibernate.Criteria probandCriteria = createProbandCriteria(null);
	org.hibernate.Criteria particularsCriteria;
	if (person) {
		particularsCriteria = probandCriteria.createCriteria("personParticulars", "particulars");
	} else {
		particularsCriteria = probandCriteria.createCriteria("animalParticulars", "particulars");
	}
	particularsCriteria.add(Restrictions.like("alias", aliasPattern, MatchMode.EXACT));
	probandCriteria.addOrder(Order.desc("particulars.alias"));
	probandCriteria.setMaxResults(1);
	return (Proband) probandCriteria.uniqueResult();
}
 
Example #25
Source File: InquiryValueDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void applySortOrders(org.hibernate.Criteria inquiryCriteria) {
	if (inquiryCriteria != null) {
		inquiryCriteria.addOrder(Order.asc("trial"));
		inquiryCriteria.addOrder(Order.asc("category"));
		inquiryCriteria.addOrder(Order.asc("position"));
	}
}
 
Example #26
Source File: SQLVisitor.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Object visitOrderByExpression(OrderByExpression order_expression,
      String expression_string, List<Object> orders)
{
   for (Object object: orders)
   {
      Order order = Order.class.cast(object);
      criteria.addOrder(order);
   }
   return criteria;
}
 
Example #27
Source File: DatabaseMatrixStorage.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
   @Override
public IMatrix getMatrixById(long matrixId) {
	Session session = null;
	Criteria query = null;
	List<StoredMatrix> list  = null;

	try {

		session = sessionFactory.openSession();
		query = session.createCriteria(StoredMatrix.class).add(Restrictions.idEq(matrixId));
		query.addOrder(Order.desc("id"));
		list = query.list();

	} catch (HibernateException e) {

		logger.error(e.getMessage(), e);
		throw new StorageException("Can't load matrix descriptor from DB", e);

	} finally {
		if (session != null) {
			session.close();
		}
	}

       return !list.isEmpty() ? convertFromStoredMatrix(list.get(0)) : null;
   }
 
Example #28
Source File: FooSortingPersistenceIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void whenHQLCriteriaSortingByOneAttr_thenPrintSortedResults() {
    final Criteria criteria = session.createCriteria(Foo.class, "FOO");
    criteria.addOrder(Order.asc("id"));
    final List<Foo> fooList = criteria.list();
    for (final Foo foo : fooList) {
        System.out.println("Id: " + foo.getId() + ", FirstName: " + foo.getName());
    }
}
 
Example #29
Source File: SakaiPersonManagerImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * @see SakaiPersonManager#findSakaiPerson(String)
 */
public List findSakaiPerson(final String simpleSearchCriteria)
{
	if (log.isDebugEnabled())
	{
		log.debug("findSakaiPerson(String {})", simpleSearchCriteria);
	}
	if (simpleSearchCriteria == null || simpleSearchCriteria.length() < 1)
		throw new IllegalArgumentException("Illegal simpleSearchCriteria argument passed!");

	final String match = PERCENT_SIGN + simpleSearchCriteria + PERCENT_SIGN;
	final HibernateCallback hcb = new HibernateCallback()
	{
		public Object doInHibernate(Session session) throws HibernateException
		{
			final Criteria c = session.createCriteria(SakaiPersonImpl.class);
			c.add(Expression.disjunction().add(Expression.ilike(UID, match)).add(Expression.ilike(GIVENNAME, match)).add(
					Expression.ilike(SURNAME, match)));
			c.addOrder(Order.asc(SURNAME));
			// c.setCacheable(cacheFindSakaiPersonString);
			return c.list();
			
		}
	};

	log.debug("return getHibernateTemplate().executeFind(hcb);");
	List hb = (List) getHibernateTemplate().execute(hcb);
	if (photoService.overRidesDefault()) {
		return getDiskPhotosForList(hb);
	} else {
		return hb;
	}
}
 
Example #30
Source File: SbiMetaBcDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load paginated tables.
 *
 * @return List of meta tables
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaTableDAOHibImpl#loadAllTables()
 */
@Override
public List<SbiMetaBc> loadPaginatedMetaBC(Integer page, Integer item_per_page, String search) throws EMFUserError {
	logger.debug("IN");

	Session tmpSession = null;
	Transaction tx = null;
	List<SbiMetaBc> toReturn = new ArrayList();
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Criteria c = tmpSession.createCriteria(SbiMetaBc.class);
		c.addOrder(Order.asc("name"));

		c.setFirstResult((page - 1) * item_per_page);
		c.setMaxResults(item_per_page);

		c.add(Restrictions.like("name", search == null ? "" : search, MatchMode.ANYWHERE).ignoreCase());
		tx.commit();
		toReturn = c.list();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}

	}
	logger.debug("OUT");
	return toReturn;
}