List of usage examples for org.hibernate.criterion Projections distinct
public static Projection distinct(Projection projection)
From source file:org.generationcp.middleware.dao.GermplasmListDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<GermplasmList> getByGID(final Integer gid, final int start, final int numOfRows) { try {/* w ww .j ava 2s . c o m*/ if (gid != null) { final Criteria criteria = this.getSession().createCriteria(GermplasmListData.class); criteria.createAlias("list", "l"); criteria.setProjection(Projections.distinct(Projections.property("list"))); criteria.add(Restrictions.eq("gid", gid)); criteria.add(Restrictions.ne("l.status", GermplasmListDAO.STATUS_DELETED)); criteria.setFirstResult(start); criteria.setMaxResults(numOfRows); criteria.addOrder(Order.asc("l.id")); criteria.addOrder(Order.asc("entryId")); return criteria.list(); } } catch (final HibernateException e) { final String errorMessage = "Error with getByGid(gid=" + gid + ") query from GermplasmList: " + e.getMessage(); GermplasmListDAO.LOG.error(errorMessage); throw new MiddlewareQueryException(errorMessage, e); } return new ArrayList<>(); }
From source file:org.generationcp.middleware.dao.NumericDataDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<Integer> getObservationUnitIdsByTraitScaleMethodAndValueCombinations( List<TraitCombinationFilter> filters, int start, int numOfRows) throws MiddlewareQueryException { try {// w w w . j ava 2 s. c om if (filters == null || filters.isEmpty()) { return new ArrayList<Integer>(); } Criteria criteria = getSession().createCriteria(NumericData.class); criteria.createAlias("variate", "variate"); criteria.setProjection(Projections.distinct(Projections.property("id.observationUnitId"))); // keeps track if at least one filter was added boolean filterAdded = false; for (TraitCombinationFilter combination : filters) { Object value = combination.getValue(); // accept only Double objects if (value instanceof Double || value instanceof NumericRange) { criteria.add(Restrictions.eq("variate.traitId", combination.getTraitId())); criteria.add(Restrictions.eq("variate.scaleId", combination.getScaleId())); criteria.add(Restrictions.eq("variate.methodId", combination.getMethodId())); if (value instanceof NumericRange) { NumericRange range = (NumericRange) value; if (range.getStart() != null) { criteria.add(Restrictions.gt("value", range.getStart())); } if (range.getEnd() != null) { criteria.add(Restrictions.lt("value", range.getEnd())); } } else { criteria.add(Restrictions.eq("value", combination.getValue())); } filterAdded = true; } } if (filterAdded) { // if there is at least one filter, execute query and return results criteria.setFirstResult(start); criteria.setMaxResults((numOfRows)); return criteria.list(); } else { // return empty list if no filter was added return new ArrayList<Integer>(); } } catch (HibernateException e) { throw new MiddlewareQueryException( "Error with get getObservationUnitIdsByTraitScaleMethodAndValueCombinations(filters=" + filters + ") query from NumericData: " + e.getMessage(), e); } }
From source file:org.generationcp.middleware.dao.OindexDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<Integer> getOunitIDsByRepresentationId(Integer representationId, int start, int numOfRows) throws MiddlewareQueryException { try {/* w w w . jav a 2s .c o m*/ Criteria criteria = getSession().createCriteria(Oindex.class); criteria.add(Restrictions.eq("representationNumber", representationId)); criteria.setProjection(Projections.distinct(Projections.property("observationUnitId"))); criteria.setFirstResult(start); criteria.setMaxResults(numOfRows); List<Integer> ounitIDs = criteria.list(); return ounitIDs; } catch (HibernateException e) { throw new MiddlewareQueryException("Error with getOunitIDsByRepresentationId(representationId=" + representationId + ")query from Oindex: " + e.getMessage(), e); } }
From source file:org.generationcp.middleware.dao.ProjectUserRoleDAO.java
License:Open Source License
@SuppressWarnings("unchecked") public List<Project> getProjectsByUser(User user) throws MiddlewareQueryException { try {// w w w. ja v a 2 s . c o m Criteria criteria = getSession().createCriteria(ProjectUserRole.class); criteria.add(Restrictions.eq("userId", user.getUserid())); criteria.setProjection(Projections.distinct(Projections.property("project"))); return criteria.list(); } catch (HibernateException e) { throw new MiddlewareQueryException( "Error in getProjectsByUser(user=" + user + ") query from Project: " + e.getMessage(), e); } }
From source file:org.geolatte.featureserver.dbase.DbaseFacade.java
License:Open Source License
public <T> List<T> getDistinctValues(Class<?> entityClass, String property, Class<T> propertyType) { Transaction tx = null;/*w ww . j av a 2s . c o m*/ try { Session session = sessionFactory.getCurrentSession(); tx = session.beginTransaction(); Criteria criteria = session.createCriteria(entityClass); criteria.add(Restrictions.isNotNull(property)); criteria.setProjection(Projections.distinct(Projections.property(property))); List<T> result = (List<T>) criteria.list(); tx.commit(); return result; } catch (HibernateException e) { LOGGER.error(e); if (tx != null) { tx.rollback(); } throw new DatabaseException(e); } finally { sessionFactory.getCurrentSession().close(); } }
From source file:org.jahia.modules.ugp.showcase.persistence.DataInitializer.java
License:Open Source License
private void populateData() throws IOException { logger.info("Populating showcase DB schema data..."); List<String> data = readInitialData(); Session hibSession = sessionFactoryBean.openSession(); try {/* w w w . j av a2 s . c om*/ hibSession.beginTransaction(); for (String line : data) { User user = toUser(line); if (user != null) { hibSession.save(user); } } hibSession.getTransaction().commit(); hibSession.beginTransaction(); @SuppressWarnings("unchecked") List<String> lastNames = hibSession.createCriteria(UserProperty.class) .setProjection(Projections.distinct(Projections.property("value"))) .add(Restrictions.eq("name", "j:lastName")).list(); logger.info("Found {} distinct last names. Creating groups...", lastNames.size()); for (String lastName : lastNames) { Group g = new Group("group-" + lastName.toLowerCase()); @SuppressWarnings("unchecked") List<User> users = hibSession.createCriteria(User.class).createCriteria("properties") .add(Restrictions.eq("name", "j:lastName")).add(Restrictions.eq("value", lastName)).list(); if (users.size() > 0) { for (User u : users) { g.addMember(new GroupMember(u.getUsername())); } } hibSession.save(g); } hibSession.getTransaction().commit(); logger.info("...done populating showcase DB schema data"); } catch (RuntimeException e) { hibSession.getTransaction().rollback(); throw e; } finally { hibSession.close(); } }
From source file:org.jasig.ssp.dao.EarlyAlertDao.java
License:Apache License
@SuppressWarnings("unchecked") public PagingWrapper<EarlyAlertStudentReportTO> getStudentsEarlyAlertCountSetForCriteria( EarlyAlertStudentSearchTO criteriaTO, SortingAndPaging sAndP) { final Criteria query = createCriteria(); setPersonCriteria(query.createAlias("person", "person"), criteriaTO.getAddressLabelSearchTO()); if (criteriaTO.getTermCode() != null) { query.add(Restrictions.eq("courseTermCode", criteriaTO.getTermCode())); }//from ww w.ja v a 2 s . co m if (criteriaTO.getStartDate() != null) { query.add(Restrictions.ge("createdDate", criteriaTO.getStartDate())); } if (criteriaTO.getEndDate() != null) { query.add(Restrictions.le("createdDate", criteriaTO.getEndDate())); } query.setProjection(null); List<UUID> ids = query.setProjection(Projections.distinct(Projections.property("id"))).list(); if (ids.size() <= 0) { return null; } BatchProcessor<UUID, EarlyAlertStudentReportTO> processor = new BatchProcessor<UUID, EarlyAlertStudentReportTO>( ids, sAndP); do { final Criteria criteria = createCriteria(); ProjectionList projections = Projections.projectionList() .add(Projections.countDistinct("id").as("earlyalert_total")) .add(Projections.countDistinct("closedBy").as("earlyalert_closed")); addBasicStudentProperties(projections, criteria); projections.add(Projections.groupProperty("id").as("earlyalert_earlyAlertId")); criteria.setProjection(projections); criteria.setResultTransformer( new NamespacedAliasToBeanResultTransformer(EarlyAlertStudentReportTO.class, "earlyalert_")); processor.process(criteria, "id"); } while (processor.moreToProcess()); return processor.getSortedAndPagedResults(); }
From source file:org.jasig.ssp.dao.EarlyAlertResponseDao.java
License:Apache License
@SuppressWarnings(UNCHECKED) public List<EarlyAlertStudentReportTO> getPeopleByEarlyAlertReferralIds(final List<UUID> earlyAlertReferralIds, final String alertTermCode, final Date alertCreateDateFrom, final Date alertCreateDateTo, final Date responseCreateDateFrom, final Date responseCreateDateTo, final PersonSearchFormTO personSearchForm, final SortingAndPaging sAndP) throws ObjectNotFoundException { final Criteria criteria = createCriteria(); criteria.createAlias("earlyAlertReferralIds", "earlyAlertReferral"); criteria.createAlias("earlyAlert", "earlyAlert"); if (alertTermCode != null) { criteria.add(Restrictions.eq("earlyAlert.courseTermCode", alertTermCode)); }/*from ww w. ja v a 2 s .co m*/ if (alertCreateDateFrom != null) { criteria.add(Restrictions.ge("earlyAlert.createdDate", alertCreateDateFrom)); } if (alertCreateDateTo != null) { criteria.add(Restrictions.le("earlyAlert.createdDate", alertCreateDateTo)); } if (responseCreateDateFrom != null) { criteria.add(Restrictions.ge("createdDate", responseCreateDateFrom)); } if (responseCreateDateTo != null) { criteria.add(Restrictions.le("createdDate", responseCreateDateTo)); } if (earlyAlertReferralIds != null) { // EarlyAlertResponse->EarlyAlertReferral not modeled as an operational // join type, so no filtering on object status since for a direct // operational->reference association, the status of the reference type // does not matter criteria.add(Restrictions.in("earlyAlertReferral.id", earlyAlertReferralIds)); } Criteria personCriteria = criteria.createAlias("earlyAlert.person", "person"); setPersonCriteria(personCriteria, personSearchForm); List<UUID> ids = criteria.setProjection(Projections.distinct(Projections.property("id"))).list(); if (ids.size() == 0) { return new ArrayList<>(); } BatchProcessor<UUID, EarlyAlertStudentReportTO> processor = new BatchProcessor<UUID, EarlyAlertStudentReportTO>( ids); do { final Criteria collectionCriteria = createCriteria(); collectionCriteria.createAlias("earlyAlert", "earlyAlert"); collectionCriteria.createAlias("earlyAlert.person", "person"); collectionCriteria.createAlias("person.coach", "coach"); ProjectionList projections = Projections.projectionList().add(Projections .distinct(Projections.groupProperty("earlyAlert.id").as("early_alert_response_earlyAlertId"))); addBasicStudentProperties(projections, collectionCriteria); collectionCriteria.addOrder(Order.asc("person.lastName")); collectionCriteria.addOrder(Order.asc("person.firstName")); collectionCriteria.addOrder(Order.asc("person.middleName")); collectionCriteria.setProjection(projections).setResultTransformer( new NamespacedAliasToBeanResultTransformer(EarlyAlertStudentReportTO.class, "early_alert_response_")); processor.process(collectionCriteria, "id"); } while (processor.moreToProcess()); return processor.getSortedAndPagedResultsAsList(); }
From source file:org.jasig.ssp.dao.external.ExternalPersonDao.java
License:Apache License
@SuppressWarnings("unchecked") public List<String> getAllDepartmentNames() { final Criteria query = createCriteria(); query.setProjection(/*from www . j ava2 s. co m*/ Projections.projectionList().add(Projections.distinct(Projections.property("departmentName")))); return (List<String>) query.list(); }
From source file:org.jasig.ssp.dao.JournalEntryDao.java
License:Apache License
@SuppressWarnings("unchecked") public PagingWrapper<JournalStepStudentReportTO> getJournalStepStudentReportTOsFromCriteria( JournalStepSearchFormTO personSearchForm, SortingAndPaging sAndP) { final Criteria criteria = createCriteria(sAndP); setPersonCriteria(criteria, personSearchForm); if (personSearchForm.getCreateDateFrom() != null) { criteria.add(Restrictions.ge("createdDate", personSearchForm.getCreateDateFrom())); }//from w w w. j a v a 2 s .co m if (personSearchForm.getCreateDateTo() != null) { criteria.add(Restrictions.le("createdDate", personSearchForm.getCreateDateTo())); } if (personSearchForm.getGetStepDetails()) { JoinType joinType = JoinType.INNER_JOIN; criteria.createAlias("journalEntryDetails", "journalEntryDetails", joinType); criteria.createAlias("journalEntryDetails.journalStepJournalStepDetail", "journalStepJournalStepDetail", joinType); criteria.createAlias("journalStepJournalStepDetail.journalStepDetail", "journalStepDetail", joinType); if (personSearchForm.getJournalStepDetailIds() != null && !personSearchForm.getJournalStepDetailIds().isEmpty()) { criteria.add(Restrictions.in("journalStepDetail.id", personSearchForm.getJournalStepDetailIds())); criteria.add(Restrictions.eq("journalEntryDetails.objectStatus", sAndP.getStatus())); criteria.add(Restrictions.eq("journalStepJournalStepDetail.objectStatus", sAndP.getStatus())); } } else { criteria.createAlias("journalEntryDetails", "journalEntryDetails", JoinType.LEFT_OUTER_JOIN); criteria.createAlias("journalEntryDetails.journalStepJournalStepDetail", "journalStepJournalStepDetail", JoinType.LEFT_OUTER_JOIN); criteria.createAlias("journalStepJournalStepDetail.journalStepDetail", "journalStepDetail", JoinType.LEFT_OUTER_JOIN); if (personSearchForm.getJournalStepDetailIds() != null && !personSearchForm.getJournalStepDetailIds().isEmpty()) { Criterion isNotIds = Restrictions .not(Restrictions.in("journalStepDetail.id", personSearchForm.getJournalStepDetailIds())); Criterion isNull = Restrictions.isNull("journalStepDetail.id"); criteria.add(Restrictions.or(isNotIds, isNull)); } else { criteria.add(Restrictions.isNull("journalStepDetail.id")); } } ProjectionList projections = Projections.projectionList(); projections.add(Projections.distinct( Projections.groupProperty("journalEntryDetails.id").as("journalentry_journalEntryDetailId"))); addBasicStudentProperties(projections, criteria); projections .add(Projections.groupProperty("journalStepDetail.name").as("journalentry_journalStepDetailName")); criteria.setProjection(projections); criteria.setResultTransformer( new NamespacedAliasToBeanResultTransformer(JournalStepStudentReportTO.class, "journalentry_")); if (criteria.list().size() > 1) { List<JournalStepStudentReportTO> reports = criteria.list(); Map<UUID, JournalStepStudentReportTO> cleanReports = new HashMap<UUID, JournalStepStudentReportTO>(); for (JournalStepStudentReportTO report : reports) { if (!cleanReports.containsKey(report.getJournalEntryDetailId())) { cleanReports.put(report.getJournalEntryDetailId(), report); } } List<JournalStepStudentReportTO> sortReports = Lists.newArrayList(cleanReports.values()); Collections.sort(sortReports, new Comparator<JournalStepStudentReportTO>() { public int compare(JournalStepStudentReportTO o1, JournalStepStudentReportTO o2) { JournalStepStudentReportTO p1 = (JournalStepStudentReportTO) o1; JournalStepStudentReportTO p2 = (JournalStepStudentReportTO) o2; int value = p1.getLastName().compareToIgnoreCase(p2.getLastName()); if (value != 0) return value; value = p1.getFirstName().compareToIgnoreCase(p2.getFirstName()); if (value != 0) return value; if (p1.getMiddleName() == null && p2.getMiddleName() == null) return 0; if (p1.getMiddleName() == null) return -1; if (p2.getMiddleName() == null) return 1; return p1.getMiddleName().compareToIgnoreCase(p2.getMiddleName()); } }); return new PagingWrapper<JournalStepStudentReportTO>(sortReports.size(), sortReports); } return new PagingWrapper<JournalStepStudentReportTO>(criteria.list().size(), (List<JournalStepStudentReportTO>) criteria.list()); }