org.hibernate.criterion.Projections Java Examples

The following examples show how to use org.hibernate.criterion.Projections. 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: InquiryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected Collection<String> handleFindCategories(Long trialId,
		String categoryPrefix, Boolean active, Boolean activeSignup, Integer limit) throws Exception {
	org.hibernate.Criteria inquiryCriteria = createInquiryCriteria();
	if (trialId != null) {
		inquiryCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (active != null) {
		inquiryCriteria.add(Restrictions.eq("active", active.booleanValue()));
	}
	if (activeSignup != null) {
		inquiryCriteria.add(Restrictions.eq("activeSignup", activeSignup.booleanValue()));
	}
	CategoryCriterion.apply(inquiryCriteria, new CategoryCriterion(categoryPrefix, "category", MatchMode.START));
	inquiryCriteria.addOrder(Order.asc("category"));
	inquiryCriteria.setProjection(Projections.distinct(Projections.property("category")));
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.INQUIRY_CATEGORY_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.INQUIRY_CATEGORY_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), inquiryCriteria);
	return inquiryCriteria.list();
}
 
Example #2
Source File: CollectionLogRepositoryImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public CollectionLogDataResponse getPaginatedData(Integer start, Integer limit) {
    Criteria countCriteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionLog.class);
    countCriteria.setProjection(Projections.rowCount());
    Long count = (Long) countCriteria.uniqueResult();
    if (count == 0){
        return new CollectionLogDataResponse(Collections.<CollectionLog>emptyList(), count);
    }

    Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionLog.class);
    criteria.setFirstResult(start);
    criteria.setMaxResults(limit);
    criteria.addOrder(Order.desc("startDate"));

    return new CollectionLogDataResponse(criteria.list(), count);
}
 
Example #3
Source File: AssignmentRepositoryImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public long countAssignmentSubmissions(String assignmentId, Boolean graded, Boolean hasSubmissionDate, Boolean userSubmission, List<String> userIds) {
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(AssignmentSubmission.class)
            .setProjection(Projections.countDistinct("id"))
            .add(Restrictions.eq("assignment.id", assignmentId))
            .add(Restrictions.eq("submitted", Boolean.TRUE))
            .createAlias("submitters", "s");

    if (graded != null) {
        criteria.add(Restrictions.eq("graded", graded));
    }
    if (hasSubmissionDate != null) {
        criteria.add(hasSubmissionDate ? Restrictions.isNotNull("dateSubmitted") : Restrictions.isNull("dateSubmitted"));
    }
    if (userSubmission != null) {
        criteria.add(Restrictions.eq("userSubmission", userSubmission));
    }
    if (userIds != null) {
        if (userIds.isEmpty()) {
            return 0; // if we have an empty list then we return always return 0
        } else {
            criteria.add(HibernateCriterionUtils.CriterionInRestrictionSplitter("s.submitter", userIds));
        }
    }
    return ((Number) criteria.uniqueResult()).longValue();
}
 
Example #4
Source File: SiteDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public Pagination searchAuthAgents(final String name, final int page) {
	return (Pagination) getHibernateTemplate().execute(
			new HibernateCallback() {
				public Object doInHibernate(Session session) {
					
					Criteria query = session.createCriteria(AuthorisingAgent.class);
					Criteria cntQuery = session.createCriteria(AuthorisingAgent.class);
					
					if(name != null) { 
						query.add(Restrictions.ilike("name", name, MatchMode.START));
						cntQuery.add(Restrictions.ilike("name", name, MatchMode.START));
					}
					
					query.addOrder(Order.asc("name"));
					cntQuery.setProjection(Projections.rowCount());
					
					return new Pagination(cntQuery, query, page, Constants.GBL_PAGE_SIZE);
				}
			}
		);	
}
 
Example #5
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 #6
Source File: BullhornServiceImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Transactional
public long getAlertCount(String userId) {

    Long count = (Long) countCache.get(userId);

    if (count != null) {
        log.debug("bullhorn_alert_count_cache hit");
        return count;
    } else {
        log.debug("bullhorn_alert_count_cache miss");

        count = (Long) sessionFactory.getCurrentSession().createCriteria(BullhornAlert.class)
            .add(Restrictions.eq("toUser", userId))
            .add(Restrictions.eq("deferred", false))
            .setProjection(Projections.rowCount()).uniqueResult();
        countCache.put(userId, count);
        return count;
    }
}
 
Example #7
Source File: ECRFFieldValueDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetCount(Long probandListEntryId, Long ecrfId, String section, boolean excludeAuditTrail, Boolean optional) throws Exception {
	org.hibernate.Criteria ecrfFieldValueCriteria = createEcrfFieldValueCriteria("ecrfFieldValue0");
	ecrfFieldValueCriteria.add(Restrictions.eq("listEntry.id", probandListEntryId.longValue()));
	org.hibernate.Criteria ecrfFieldCriteria = ecrfFieldValueCriteria.createCriteria("ecrfField", "ecrfField0");
	ecrfFieldCriteria.add(Restrictions.eq("ecrf.id", ecrfId.longValue()));
	if (optional != null) {
		ecrfFieldCriteria.add(Restrictions.eq("optional", optional.booleanValue()));
	}
	if (section != null && section.length() > 0) {
		ecrfFieldCriteria.add(Restrictions.eq("section", section));
	} else {
		ecrfFieldCriteria.add(Restrictions.or(Restrictions.eq("section", ""), Restrictions.isNull("section")));
	}
	if (excludeAuditTrail) {
		applyEcrfFieldValueMaxIdSubCriteria(ecrfFieldValueCriteria, ecrfFieldCriteria, null, probandListEntryId, null);
	}
	return (Long) ecrfFieldValueCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #8
Source File: SiteDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
/**
* Check that the Authorising Agent name is unique.
* @param oid  The OID of the authorising agent, if available.
* @param name The name of the authorising agent.
* @return True if unique; otherwise false.
*/
  public boolean isAuthAgencyNameUnique(final Long oid, final String name) {
int count = (Integer) getHibernateTemplate().execute(
		new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Criteria query = session.createCriteria(AuthorisingAgent.class);
				
				if(oid != null) { 
					query.add(Restrictions.ne("oid", oid));
				}
				
				query.add(Restrictions.ilike("name", name, MatchMode.START))
					.setProjection(Projections.rowCount());
				
				return query.uniqueResult();
			}
		}
	);

return count == 0;
  }
 
Example #9
Source File: BaseServiceImpl.java    From S-mall-ssh with GNU General Public License v3.0 6 votes vote down vote up
/**
 * @see BaseService
 */
@Override
public int total(Object... paramAndObjects) {
    Criteria c= createCriteria();
    if(paramAndObjects.length%2 !=0){
        return 0;
    }
    for (int i=0;i<paramAndObjects.length;i+=2){
        if(paramAndObjects[i+1] == null){
            c.add(Restrictions.isNull(paramAndObjects[i].toString()));
        }else{
            c.add(Restrictions.eq(paramAndObjects[i].toString(),paramAndObjects[i+1]));
        }
    }
    c.setProjection(Projections.rowCount());
    return ((Long)c.uniqueResult()).intValue();
}
 
Example #10
Source File: ProductService.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Odata dedicated Services
 */
@Transactional(readOnly = true)
@Cacheable (value = "product_count", key = "{#criteria, #uuid}")
public int countProducts (DetachedCriteria criteria, String uuid)
{
   if (criteria == null)
   {
      criteria = DetachedCriteria.forClass (Product.class);
   }

   // count only processed products
   criteria.add (Restrictions.eq ("processed", true));

   if (uuid != null)
   {
      List<Long> product_ids = collectionService.getProductIds (uuid);
      criteria.add (Restrictions.in ("id", product_ids));
   }
   criteria.setProjection (Projections.rowCount ());
   return productDao.count (criteria);
}
 
Example #11
Source File: ProductTypeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List loadOrganizzationEngines(final String tenant) {

	List orgEngs = list(new ICriterion() {
		@Override
		public Criteria evaluate(Session session) {
			return session
					.createCriteria(SbiEngines.class)
					.createAlias("sbiProductTypeEngine", "_sbiProductTypeEngine")
					.createAlias("_sbiProductTypeEngine.sbiProductType", "_sbiProductType")
					.createAlias("_sbiProductType.sbiOrganizationProductType", "_sbiOrganizationProductType")
					.createAlias("_sbiOrganizationProductType.sbiOrganizations", "_sbiOrganizations")
					.add(Restrictions.eq("_sbiOrganizations.name", tenant))
					.setProjection(
							Projections.projectionList().add(org.hibernate.criterion.Property.forName("label").as("engineLabel"))
									.add(org.hibernate.criterion.Property.forName("_sbiProductType.label").as("productTypeLabel")))
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		}
	});
	return orgEngs;
}
 
Example #12
Source File: ProductTypeDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<String> loadCurrentTenantProductTypes() {

	List<String> orgEngs = list(new ICriterion() {
		@Override
		public Criteria evaluate(Session session) {
			Criteria criteria = session.createCriteria(SbiProductType.class);
			criteria.createAlias("sbiOrganizationProductType", "_sbiOrganizationProductType");
			criteria.createAlias("_sbiOrganizationProductType.sbiOrganizations", "_sbiOrganizations");
			criteria.add(Restrictions.eq("_sbiOrganizations.name", getTenant()));
			return criteria.setProjection(Projections.projectionList().add(org.hibernate.criterion.Property.forName("label").as("productLabel")));
		}
	});
	return orgEngs;

}
 
Example #13
Source File: ProbandListEntryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetTrialGroupProbandCount(
		Long trialId, Long probandGroupId, Long probandId, boolean total) throws Exception {
	org.hibernate.Criteria listEntryCriteria = createListEntryCriteria();
	if (trialId != null) {
		listEntryCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (probandGroupId != null) {
		listEntryCriteria.add(Restrictions.eq("group.id", probandGroupId.longValue()));
	}
	if (probandId != null) {
		listEntryCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
	}
	if (!total) {
		listEntryCriteria.createCriteria("lastStatus", CriteriaSpecification.INNER_JOIN).createCriteria("status", CriteriaSpecification.INNER_JOIN)
				.add(Restrictions.eq("count", true));
	}
	return (Long) listEntryCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #14
Source File: SearchGlossaryByName.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Criteria evaluate(Session session) {
	Criteria criteria = session.createCriteria(SbiGlGlossary.class);
	criteria.setProjection(
			Projections.projectionList().add(Projections.property("glossaryId"), "glossaryId").add(Projections.property("glossaryNm"), "glossaryNm"))
			.setResultTransformer(Transformers.aliasToBean(SbiGlGlossary.class));
	if (glossary != null && !glossary.isEmpty()) {
		criteria.add(Restrictions.like("glossaryNm", glossary, MatchMode.ANYWHERE).ignoreCase());
	}

	if (page != null && itemsPerPage != null) {
		criteria.setFirstResult((page - 1) * itemsPerPage);
		criteria.setMaxResults(itemsPerPage);
	}

	return criteria;
}
 
Example #15
Source File: NetworkUsageDao.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
public long getDownloadedSizeByUserSince (final User user, final Date date)
{
   Long result =
         getHibernateTemplate ().execute (new HibernateCallback<Long> ()
         {
            @Override
            public Long doInHibernate (Session session)
                  throws HibernateException, SQLException
            {
               Criteria criteria = session.createCriteria (
                     NetworkUsage.class);
               criteria.setProjection (Projections.sum ("size"));
               criteria.add (Restrictions.eq ("isDownload", true));
               criteria.add (Restrictions.eq ("user", user));
               criteria.add (Restrictions.gt ("date", date));
               return (Long) criteria.uniqueResult ();
            }
         });
   return (result == null) ? 0 : result;
}
 
Example #16
Source File: InTrayDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public Pagination getTasks(final User user, final List<RolePrivilege> privs, final int pageNum, final int pageSize) {
    return (Pagination) getHibernateTemplate().execute(new HibernateCallback() {
  
        public Object doInHibernate(Session aSession) throws HibernateException, SQLException {
            Criteria query = aSession.createCriteria(Task.class);
            
            Disjunction dis = Restrictions.disjunction();
            
            for(RolePrivilege userPriv: privs) {
              dis.add(Restrictions.eq("privilege", userPriv.getPrivilege()));
            }
            dis.add(Restrictions.eq("assigneeOid",user.getOid()));

            query.add(dis);
            query.createCriteria("agency").add(Restrictions.eq("oid", user.getAgency().getOid()));
            query.addOrder(Order.desc("sentDate"));
            
            Criteria cntQuery = aSession.createCriteria(Task.class);
            cntQuery.add(dis);
            cntQuery.createCriteria("agency").add(Restrictions.eq("oid", user.getAgency().getOid()));
            cntQuery.setProjection(Projections.rowCount());
            
            return new Pagination(cntQuery, query, pageNum, pageSize);
        }
    });
}
 
Example #17
Source File: KpiDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Threshold> listThreshold() {
    List<SbiKpiThreshold> sbiLst = list(new ICriterion<SbiKpiThreshold>() {
        @Override
        public Criteria evaluate(Session session) {
            return session
                    .createCriteria(SbiKpiThreshold.class)
                    .setProjection(
                            Projections.projectionList().add(Projections.property("id"), "id").add(Projections.property("name"), "name")
                                    .add(Projections.property("description"), "description"))
                    .setResultTransformer(Transformers.aliasToBean(SbiKpiThreshold.class));
        }
    });
    List<Threshold> thresholds = new ArrayList<>();
    for (SbiKpiThreshold sbiThreshold : sbiLst) {
        thresholds.add(from(sbiThreshold, false));
    }
    return thresholds;
}
 
Example #18
Source File: ECRFFieldDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetCount(Long trialId, Long ecrfId, String section, Boolean series, Boolean optional) 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()));
	}
	if (series != null) {
		ecrfFieldCriteria.add(Restrictions.eq("series", series.booleanValue()));
	}
	if (optional != null) {
		ecrfFieldCriteria.add(Restrictions.eq("optional", optional.booleanValue()));
	}
	if (section != null && section.length() > 0) {
		ecrfFieldCriteria.add(Restrictions.eq("section", section));
	} else {
		ecrfFieldCriteria.add(Restrictions.or(Restrictions.eq("section", ""), Restrictions.isNull("section")));
	}
	return (Long) ecrfFieldCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #19
Source File: ProbandListEntryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static Criteria applyStratificationTagValuesCriterions(org.hibernate.Criteria listEntryCriteria, Set<Long> selectionSetValueIds) {
	org.hibernate.Criteria tagValuesCriteria = listEntryCriteria.createCriteria("tagValues", CriteriaSpecification.INNER_JOIN);
	tagValuesCriteria.createCriteria("tag", CriteriaSpecification.INNER_JOIN).add(Restrictions.eq("stratification", true));
	org.hibernate.Criteria selectionValuesCriteria = tagValuesCriteria.createCriteria("value", CriteriaSpecification.INNER_JOIN).createCriteria("selectionValues",
			CriteriaSpecification.INNER_JOIN);
	selectionValuesCriteria.add(Restrictions.in("id", selectionSetValueIds));
	ProjectionList proj = Projections.projectionList();
	proj.add(Projections.id());
	proj.add(Projections.sqlGroupProjection(
			"count(*) as selectionValuesCount",
			"{alias}.id having count(*) = " + selectionSetValueIds.size(),
			new String[] { "selectionValuesCount" },
			new org.hibernate.type.Type[] { Hibernate.LONG }));
	listEntryCriteria.setProjection(proj);
	return listEntryCriteria;
}
 
Example #20
Source File: StaffDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetCountByDepartmentStatusInterval(Long departmentId, Timestamp from, Timestamp to, Boolean staffActive, Boolean allocatable, Boolean hideAvailability)
		throws Exception {
	org.hibernate.Criteria staffCriteria = createStaffCriteria();
	if (departmentId != null) {
		staffCriteria.add(Restrictions.eq("department.id", departmentId.longValue()));
	}
	if (allocatable != null) {
		staffCriteria.add(Restrictions.eq("allocatable", allocatable.booleanValue()));
	}
	org.hibernate.Criteria statusEntryCriteria = staffCriteria.createCriteria("statusEntries", CriteriaSpecification.INNER_JOIN);
	CriteriaUtil.applyStopOpenIntervalCriterion(statusEntryCriteria, from, to, null);
	if (staffActive != null || hideAvailability != null) {
		Criteria statusTypeCriteria = statusEntryCriteria.createCriteria("type", CriteriaSpecification.INNER_JOIN);
		if (staffActive != null) {
			statusTypeCriteria.add(Restrictions.eq("staffActive", staffActive.booleanValue()));
		}
		if (hideAvailability != null) {
			statusTypeCriteria.add(Restrictions.eq("hideAvailability", hideAvailability.booleanValue()));
		}
	}
	return (Long) staffCriteria.setProjection(Projections.countDistinct("id")).uniqueResult();
}
 
Example #21
Source File: CreditBankDAOImpl.java    From computational-economy with GNU General Public License v3.0 6 votes vote down vote up
@Override
public CreditBank findRandom(final Currency currency) {
	Criteria crit = getSession().createCriteria(CreditBankImpl.class);
	crit.add(Restrictions.eq("primaryCurrency", currency));
	crit.setProjection(Projections.rowCount());
	final int count = ((Number) crit.uniqueResult()).intValue();

	if (0 != count) {
		final int index = ApplicationContext.getInstance().getRandomNumberGenerator().nextInt(count);

		crit = getSession().createCriteria(CreditBankImpl.class);
		crit.add(Restrictions.eq("primaryCurrency", currency));
		return (CreditBankImpl) crit.setFirstResult(index).setMaxResults(1).uniqueResult();
	}

	return null;
}
 
Example #22
Source File: TargetDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public boolean isNameOk(AbstractTarget aTarget) {
	Criteria criteria = getSession().createCriteria(AbstractTarget.class);
	criteria.setProjection(Projections.rowCount());
	criteria.add(Restrictions.eq("name", aTarget.getName()));
	if (aTarget instanceof TargetGroup) {
		criteria.add(Restrictions.eq("objectType", 0));
	}
	if (aTarget instanceof Target) {
		criteria.add(Restrictions.eq("objectType", 1));
	}
	if( aTarget.getOid() != null) {
		criteria.add(Restrictions.ne("oid", aTarget.getOid()));
	}
	
	Integer count = (Integer) criteria.uniqueResult();
	
	return count.intValue() == 0;
}
 
Example #23
Source File: TeamMemberDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetCount(Long trialId, Long staffId,
		Long roleId, Boolean allocatable) throws Exception {
	org.hibernate.Criteria teamMemberCriteria = createTeamMemberCriteria();
	if (trialId != null) {
		teamMemberCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (staffId != null) {
		teamMemberCriteria.add(Restrictions.eq("staff.id", staffId.longValue()));
	}
	if (allocatable != null) {
		org.hibernate.Criteria staffCriteria = teamMemberCriteria.createCriteria("staff");
		staffCriteria.add(Restrictions.eq("allocatable", allocatable.booleanValue()));
	}
	if (roleId != null) {
		teamMemberCriteria.add(Restrictions.eq("role.id", roleId.longValue()));
	}
	return (Long) teamMemberCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #24
Source File: BaseHibernateManager.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
protected void updateAssignment(final GradebookAssignment assignment) throws ConflictingAssignmentNameException, HibernateException {
	// Ensure that we don't have the assignment in the session, since
	// we need to compare the existing one in the db to our edited assignment
       final Session session = getSessionFactory().getCurrentSession();
	session.evict(assignment);

	final GradebookAssignment asnFromDb = (GradebookAssignment) session.load(GradebookAssignment.class, assignment.getId());

	final Long count = (Long) session.createCriteria(GradableObject.class)
               .add(Restrictions.eq("name", assignment.getName()))
               .add(Restrictions.eq("gradebook", assignment.getGradebook()))
               .add(Restrictions.ne("id", assignment.getId()))
               .add(Restrictions.eq("removed", false))
               .setProjection(Projections.rowCount())
               .uniqueResult();
	if(count > 0) {
		throw new ConflictingAssignmentNameException("You can not save multiple assignments in a gradebook with the same name");
	}

	session.evict(asnFromDb);
	session.update(assignment);
}
 
Example #25
Source File: TargetInstanceDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public int countTargetInstances(final String aUsername, final ArrayList<String> aStates) {
	return (Integer) getHibernateTemplate().execute(
		new HibernateCallback() {
			public Object doInHibernate(Session session) {					
				Criteria query = session.createCriteria(TargetInstance.class);
				query.setProjection(Projections.rowCount());
									
				if (aStates != null && !aStates.isEmpty()) {
					Disjunction stateDisjunction = Restrictions.disjunction();
					for(String s: aStates) {
						stateDisjunction.add(Restrictions.eq("state", s));
					}
					query.add(stateDisjunction);
				}
				
				query.createCriteria("owner").add(Restrictions.eq("username", aUsername));
				
									
				Integer count = (Integer) query.uniqueResult();
                
                return count;
			}
		}
	);	
}
 
Example #26
Source File: MassMailDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected long handleGetCount(Long trialId, Long probandListStatusTypeId, Boolean locked, Long resendProbandId) throws Exception {
	org.hibernate.Criteria massMailCriteria = createMassMailCriteria("massMail0");
	if (trialId != null) {
		massMailCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (probandListStatusTypeId != null) {
		massMailCriteria.add(Restrictions.eq("probandListStatus.id", probandListStatusTypeId.longValue()));
	}
	if (locked != null) {
		massMailCriteria.createCriteria("status").add(Restrictions.eq("locked", locked.booleanValue()));
	}
	if (resendProbandId != null) {
		DetachedCriteria recipientsSubQuery = DetachedCriteria.forClass(MassMailRecipientImpl.class, "massMailRecipient1"); // IMPL!!!!
		recipientsSubQuery.setProjection(Projections.rowCount());
		recipientsSubQuery.add(Restrictions.eq("proband.id", resendProbandId.longValue()));
		recipientsSubQuery.add(Restrictions.eqProperty("massMail.id", "massMail0.id"));
		massMailCriteria.add(Restrictions.or(Restrictions.eq("probandListStatusResend", true),
				Subqueries.eq(0l, recipientsSubQuery)));
	}
	return (Long) massMailCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #27
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 6 votes vote down vote up
/**
 * Get All the APPS with the launch date null
 */
public static Set<Integer> getAppsLauchDateNull(int envId) {

	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria healthCheckCriteria = session.createCriteria(HealthCheckEntity.class, "health");
	healthCheckCriteria.createCriteria("health.component", "component");
	healthCheckCriteria.add(Restrictions.isNull("health.createdDate"));
	healthCheckCriteria.add(Restrictions.eq("health.environment.environmentId", envId));
	
	ProjectionList projectionList = Projections.projectionList();
       projectionList.add(Projections.property("component.componentId"));
       healthCheckCriteria.setProjection(projectionList);
       
       Set<Integer> compSet = new HashSet<Integer>();
	@SuppressWarnings("unchecked")
	List<Integer> resultList = (List<Integer>) healthCheckCriteria.list();
	compSet.addAll(resultList); 
	txn.commit();
	return compSet;         
}
 
Example #28
Source File: HibernateDocumentDao.java    From livingdoc-confluence with GNU General Public License v3.0 5 votes vote down vote up
@Override
public List<Execution> getSpecificationExecutions(Specification specification, SystemUnderTest sut, int maxResults) {
    final Criteria crit = sessionService.getSession().createCriteria(Execution.class);

    crit.add(Restrictions.eq(SPECIFICATION_ID, specification.getId()));

    if (sut != null) {
        crit.add(Restrictions.eq(SUT_ID, sut.getId()));
    }

    // Using projections to reduce complexity of query
    crit.setProjection(Projections.projectionList()
            .add(Projections.property(EXECUTION_ID), EXECUTION_ID)
            .add(Projections.property(EXECUTION_DATE), EXECUTION_DATE)
            .add(Projections.property(EXECUTION_ERRORS), EXECUTION_ERRORS)
            .add(Projections.property(EXECUTION_FAILURES), EXECUTION_FAILURES)
            .add(Projections.property(EXECUTION_SUCCESS), EXECUTION_SUCCESS)
            .add(Projections.property(EXECUTION_IGNORED), EXECUTION_IGNORED)
            .add(Projections.property(EXECUTION_SECTIONS), EXECUTION_SECTIONS)
            .add(Projections.property(EXECUTION_ERRORID), EXECUTION_ERRORID)
    ).setResultTransformer(Transformers.aliasToBean(Execution.class));

    /* crit.add(Restrictions.or(Restrictions.or(Restrictions.not(
     * Restrictions . eq("errors", 0)),
     * Restrictions.not(Restrictions.eq("success", 0))),
     * Restrictions.or(Restrictions.not(Restrictions.eq("ignored", 0)),
     * Restrictions.not(Restrictions.eq("failures", 0))))); */

    crit.addOrder(Order.desc(EXECUTION_DATE));
    crit.setMaxResults(maxResults);

    @SuppressWarnings(SUPPRESS_UNCHECKED)
    List<Execution> executions = crit.list();
    HibernateLazyInitializer.initCollection(executions);
    Collections.reverse(executions);
    return executions;
}
 
Example #29
Source File: HibernateGenericDao.java    From lemon with Apache License 2.0 5 votes vote down vote up
/**
 * 获得总记录数.
 * 
 * @param criteria
 *            条件
 * @return 总数
 */
@Transactional(readOnly = true)
public Integer getCount(Criteria criteria) {
    Object result = criteria.setProjection(Projections.rowCount())
            .uniqueResult();

    return HibernateUtils.getNumber(result);
}
 
Example #30
Source File: DataTableColumnDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected long handleGetCount(Long userId, String tableName, String columnName) throws Exception {
	org.hibernate.Criteria tableColumnCriteria = createDataTableColumnCriteria();
	tableColumnCriteria.add(Restrictions.eq("user.id", userId.longValue()));
	if (tableName != null) {
		tableColumnCriteria.add(Restrictions.eq("tableName", tableName));
	}
	if (columnName != null) {
		tableColumnCriteria.add(Restrictions.eq("columnName", columnName));
	}
	return (Long) tableColumnCriteria.setProjection(Projections.rowCount()).uniqueResult();
}