org.hibernate.criterion.Restrictions Java Examples

The following examples show how to use org.hibernate.criterion.Restrictions. 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<Inquiry> handleFindByDepartmentActiveExcelSorted(Long departmentId, Boolean active, Boolean activeSignup, Boolean excel, Boolean values) throws Exception {
	org.hibernate.Criteria inquiryCriteria = createInquiryCriteria();
	if (departmentId != null) {
		inquiryCriteria.createCriteria("trial").add(Restrictions.eq("department.id", departmentId.longValue()));
	}
	if (active != null) {
		inquiryCriteria.add(Restrictions.eq("active", active.booleanValue()));
	}
	if (activeSignup != null) {
		inquiryCriteria.add(Restrictions.eq("activeSignup", activeSignup.booleanValue()));
	}
	if (excel != null) {
		inquiryCriteria.add(Restrictions.or(Restrictions.eq("excelValue", excel.booleanValue()),
				Restrictions.eq("excelDate", excel.booleanValue())));
	}
	if (values != null) {
		if (values) {
			inquiryCriteria.add(Restrictions.sizeGt("inquiryValues", 0));
		} else {
			inquiryCriteria.add(Restrictions.sizeEq("inquiryValues", 0));
		}
	}
	applySortOrders(inquiryCriteria);
	return inquiryCriteria.list();
}
 
Example #2
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 #3
Source File: ECRFFieldDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected Collection<ECRFField> handleFindAllSorted(String nameInfix, Integer limit) throws Exception {
	org.hibernate.Criteria ecrfFieldCriteria = createEcrfFieldCriteria();
	if (!CommonUtil.isEmptyString(nameInfix)) {
		org.hibernate.Criteria trialCriteria = ecrfFieldCriteria.createCriteria("trial", "trial0", CriteriaSpecification.INNER_JOIN);
		org.hibernate.Criteria ecrfCriteria = ecrfFieldCriteria.createCriteria("ecrf", "ecrf0", CriteriaSpecification.INNER_JOIN);
		org.hibernate.Criteria fieldCriteria = ecrfFieldCriteria.createCriteria("field", "inputField", CriteriaSpecification.INNER_JOIN);
		ecrfFieldCriteria.add(Restrictions.or(
				(new CategoryCriterion(nameInfix, "section", MatchMode.ANYWHERE)).getRestriction(),
				Restrictions.or(
						(new CategoryCriterion(nameInfix, "inputField.nameL10nKey", MatchMode.ANYWHERE)).getRestriction(),
						Restrictions.or(
								(new CategoryCriterion(nameInfix, "ecrf0.name", MatchMode.ANYWHERE)).getRestriction(),
								(new CategoryCriterion(nameInfix, "trial0.name", MatchMode.ANYWHERE)).getRestriction()))));
	}
	applySortOrders(ecrfFieldCriteria);
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.ECRF_FIELD_FIELD_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.ECRF_FIELD_FIELD_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), ecrfFieldCriteria);
	return ecrfFieldCriteria.list();
}
 
Example #4
Source File: CustomUiTemplateResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<CustomUiTemplateDTO> getCustomUITemplateBasedOnTypeByCrisisID(long crisisID, int templateType) {

	logger.info("getCustomUITemplateBasedOnTypeByCrisisID: " + crisisID + "-" + templateType );
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisID",crisisID))
			.add(Restrictions.eq("templateType", templateType));
	
	List<CustomUiTemplateDTO> dtoList = null;
	try {
		List<CustomUiTemplate> customUITemplates = this.getAllByCriteria(criterion);
		if (customUITemplates != null) {
			dtoList = new ArrayList<CustomUiTemplateDTO>(0);
			for (CustomUiTemplate c: customUITemplates) {
				CustomUiTemplateDTO dto = new CustomUiTemplateDTO(c);
				dtoList.add(dto);
			}
		}
		return dtoList;
	} catch (Exception e) {
		logger.error("Error in getCustomUITemplateBasedOnTypeByCrisisID for crisisID : " + crisisID);
		return null;
	}
}
 
Example #5
Source File: InTrayDAOImpl.java    From webcurator with Apache License 2.0 6 votes vote down vote up
public int countTasks(final User user, final List<RolePrivilege> privs) {
 	return (Integer) getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
	
	Criteria query = session.createCriteria(Task.class);
	query.setProjection(Projections.rowCount());
             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()));
                             
             Integer count = (Integer) query.uniqueResult();
             
             return count;
}
 	});
 }
 
Example #6
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 #7
Source File: CustomUiTemplateResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<CustomUiTemplateDTO> getCustomUITemplateByCrisisIDAndAttributeID(long crisisID, long attributeID) {
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisID",crisisID))
			.add(Restrictions.eq("nominalAttributeID", attributeID));
	
	List<CustomUiTemplateDTO> dtoList = null;
	try {
		List<CustomUiTemplate> customUITemplates = this.getAllByCriteria(criterion);
		if (customUITemplates != null) {
			dtoList = new ArrayList<CustomUiTemplateDTO>(0);
			for (CustomUiTemplate c: customUITemplates) {
				CustomUiTemplateDTO dto = new CustomUiTemplateDTO(c);
				dtoList.add(dto);
			}
		}
		return dtoList;
	} catch (Exception e) {
		logger.error("Error in getCustomUITemplateByCrisisIDAndAttributeID "
				+ "crisisID : " + crisisID + " and attributeID : " + attributeID);
		return null;
	}
}
 
Example #8
Source File: QuestionDAO.java    From mamute with Apache License 2.0 6 votes vote down vote up
public List<Question> top(String section, int count, DateTime since) {
	Order order;
	if (section.equals("viewed")) {
		order = Order.desc("q.views");
	}
	else if (section.equals("answered")) {
		order = Order.desc("q.answerCount");
	}
	else /*if (section.equals("voted"))*/ {
		order = Order.desc("q.voteCount");
	}
	return session.createCriteria(Question.class, "q")
			.add(and(Restrictions.eq("q.moderationOptions.invisible", false)))
			.add(gt("q.createdAt", since))
			.addOrder(order)
			.setMaxResults(count)
			.list();
}
 
Example #9
Source File: EqualOperator.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Criterion getHibernateCriterion( QueryPath queryPath )
{
    Property property = queryPath.getProperty();

    if ( property.isCollection() )
    {
        Integer value = QueryUtils.parseValue( Integer.class, args.get( 0 ) );

        if ( value == null )
        {
            throw new QueryException( "Left-side is collection, and right-side is not a valid integer, so can't compare by size." );
        }

        return Restrictions.sizeEq( queryPath.getPath(), value );
    }

    return Restrictions.eq( queryPath.getPath(), args.get( 0 ) );
}
 
Example #10
Source File: SignupMeetingDaoImpl.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
@Override
public List<String> getAllCategories(String siteId) throws DataAccessException {
	DetachedCriteria criteria = DetachedCriteria.forClass(
			SignupMeeting.class).setProjection(Projections.distinct(Projections.projectionList()
				    	    .add(Projections.property("category"), "category") )).setResultTransformer(
			Criteria.DISTINCT_ROOT_ENTITY)				
			.addOrder(Order.asc("category")).createCriteria("signupSites")
			.add(Restrictions.eq("siteId", siteId));
	
	List<String> categorys = (List<String>) getHibernateTemplate().findByCriteria(criteria);
	
	if(categorys !=null && !categorys.isEmpty()){
		return categorys;
	}
	
	return null;
}
 
Example #11
Source File: DefaultIssueManager.java    From onedev with MIT License 6 votes vote down vote up
@Sessional
@Override
public List<Issue> query(Project project, String term, int count) {
	EntityCriteria<Issue> criteria = newCriteria();
	
	Set<Project> projects = Sets.newHashSet(project);
	projects.addAll(project.getForkParents().stream().filter(it->SecurityUtils.canAccess(it)).collect(Collectors.toSet()));
	criteria.add(Restrictions.in(Issue.PROP_PROJECT, projects));
	
	if (term.startsWith("#"))
		term = term.substring(1);
	if (term.length() != 0) {
		try {
			long buildNumber = Long.parseLong(term);
			criteria.add(Restrictions.eq(Issue.PROP_NUMBER, buildNumber));
		} catch (NumberFormatException e) {
			criteria.add(Restrictions.or(
					Restrictions.ilike(Issue.PROP_TITLE, term, MatchMode.ANYWHERE),
					Restrictions.ilike(Issue.PROP_NO_SPACE_TITLE, term, MatchMode.ANYWHERE)));
		}
	}

	criteria.addOrder(Order.desc(Issue.PROP_PROJECT));
	criteria.addOrder(Order.desc(Issue.PROP_NUMBER));
	return query(criteria, 0, count);
}
 
Example #12
Source File: AccessTokenSqlMapDao.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Override
public List<AccessToken> findAllTokensForUser(String username, AccessTokenFilter filter) {
    return (List<AccessToken>) transactionTemplate.execute((TransactionCallback) transactionStatus ->
    {
        Criteria criteria = sessionFactory
                .getCurrentSession()
                .createCriteria(AccessToken.class)
                .add(Restrictions.eq("username", username))
                .add(Restrictions.eq("deletedBecauseUserDeleted", false));

        filter.applyTo(criteria);

        return criteria
                .setCacheable(true)
                .list();
    });
}
 
Example #13
Source File: KpiDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<TargetValue> listKpiWithTarget(final Integer targetId) {
    List<SbiKpiTargetValue> lst = list(new ICriterion<SbiKpiTargetValue>() {
        @Override
        public Criteria evaluate(Session session) {
            return session.createCriteria(SbiKpiTargetValue.class).createAlias("sbiKpiKpi", "sbiKpiKpi", JoinFragment.RIGHT_OUTER_JOIN)
                    .createAlias("sbiKpiTarget", "sbiKpiTarget").add(Restrictions.eq("sbiKpiKpi.active", 'T'))
                    .add(Restrictions.eq("sbiKpiTarget.targetId", targetId));
            /*
             * return session .createCriteria(SbiKpiKpi.class) .createAlias("sbiKpiTargetValues", "sbiKpiTargetValues", JoinFragment.LEFT_OUTER_JOIN)
             * .createAlias("sbiKpiTargetValues.sbiKpiKpi", "sbiKpiKpi") .add(Restrictions.eq("active", 'T')) .setProjection(
             * Projections.projectionList().add(Property.forName("sbiKpiKpiId.id").as("kpiId"))
             * .add(Property.forName("sbiKpiKpiId.version").as("kpiVersion")) .add(Property.forName("sbiKpiTargetValues.value").as("value")))
             * .setResultTransformer(Transformers.aliasToBean(SbiKpiTargetValue.class));
             */
        }
    });
    List<TargetValue> ret = new ArrayList<>();
    for (SbiKpiTargetValue sbiTarget : lst) {
        ret.add(from(sbiTarget));
    }
    return ret;
}
 
Example #14
Source File: CriteriaUtil.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static org.hibernate.criterion.Criterion getRestrictionCriterion(RestrictionCriterionTypes restriction, String propertyName, Object value,
		org.hibernate.type.NullableType type) {
	if (PROPERTY_NAME_REGEXP.matcher(propertyName).find()) {
		switch (restriction) {
			case GT:
				return Restrictions.gt(propertyName, value);
			case GE:
				return Restrictions.ge(propertyName, value);
			case LT:
				return Restrictions.lt(propertyName, value);
			case LE:
				return Restrictions.le(propertyName, value);
			default:
				throw new IllegalArgumentException(MessageFormat.format(UNSUPPORTED_BINARY_RESTRICTION_CRITERION_TYPE, restriction.toString()));
		}
	} else {
		return Restrictions.sqlRestriction(MessageFormat.format(restriction.toString(), propertyName),
				//"  "substr({alias}.logical_path, 1, length(?)) = ?",
				new Object[] { value },
				new org.hibernate.type.NullableType[] { type });
	}
}
 
Example #15
Source File: TagDataStatisticsResourceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<TagData> getDataAfterTimestamp(String crisisCode, String attributeCode, String labelCode, Long timestamp) {
	Criteria criteria = getCurrentSession().createCriteria(TagData.class);
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisCode", crisisCode))
			.add(Restrictions.eq("attributeCode", attributeCode))
			.add(Restrictions.ge("timestamp", timestamp));
	if (labelCode != null) {
		criterion = Restrictions.conjunction()
				.add(criterion)
				.add(Restrictions.eq("labelCode", labelCode));
	}

	criteria.add(criterion); 
	try {
		List<TagData> objList = (List<TagData>) criteria.list();
		return objList;
	} catch (HibernateException e) {
		logger.error("exception in getDataAfterTimestampGranularity for crisisCode : " + crisisCode
				+ " attributeCode : " + attributeCode + " timestamp : " + timestamp, e);
	}
	return null;
}
 
Example #16
Source File: ECRFFieldValueDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
protected Collection<ECRFFieldValue> handleFindByListEntryEcrfSection(Long probandListEntryId, Long ecrfId, String section, boolean sort, PSFVO psf) throws Exception {
	org.hibernate.Criteria ecrfFieldValueCriteria = createEcrfFieldValueCriteria(null);
	ecrfFieldValueCriteria.add(Restrictions.eq("listEntry.id", probandListEntryId.longValue()));
	org.hibernate.Criteria ecrfFieldCriteria = ecrfFieldValueCriteria.createCriteria("ecrfField");
	ecrfFieldCriteria.add(Restrictions.eq("ecrf.id", ecrfId.longValue()));
	if (section != null && section.length() > 0) {
		ecrfFieldCriteria.add(Restrictions.eq("section", section));
	} else {
		ecrfFieldCriteria.add(Restrictions.or(Restrictions.eq("section", ""), Restrictions.isNull("section")));
	}
	SubCriteriaMap criteriaMap = new SubCriteriaMap(ECRFFieldValue.class, ecrfFieldValueCriteria);
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	if (sort) {
		applySortOrders(null, ecrfFieldCriteria, ecrfFieldValueCriteria);
	}
	return ecrfFieldValueCriteria.list();
}
 
Example #17
Source File: KpiDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private Integer findlastKpiFromKpiValue(final Integer id) {

        return executeOnTransaction(new IExecuteOnTransaction<Integer>() {
            @Override
            public Integer execute(Session session) throws Exception {
                Criteria c = session.createCriteria(SbiKpiValue.class);
                c.add(Restrictions.eq("kpiId", id));
                c.add(Restrictions.eq("theDay", ProcessKpiJob.CARDINALITY_ALL));
                c.add(Restrictions.eq("theWeek", ProcessKpiJob.CARDINALITY_ALL));
                c.add(Restrictions.eq("theMonth", ProcessKpiJob.CARDINALITY_ALL));
                c.add(Restrictions.eq("theQuarter", ProcessKpiJob.CARDINALITY_ALL));
                // theYear is not included on this query because theYear doesn't always contain 'ALL' value
                c.setProjection(Projections.max("kpiVersion"));
                return (Integer) c.uniqueResult();
            }
        });
    }
 
Example #18
Source File: CrisisServiceImpl.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<CrisisNominalAttributeModel> getAllActiveCrisisNominalAttribute() {
	List<CrisisNominalAttributeModel> crisisNominalAttributeModelList = new ArrayList<CrisisNominalAttributeModel>();

    List<ModelFamily> modelFamilyList =  remoteModelFamilyResourceEJB.getAllByCriteria(Restrictions.eq("isActive",true)) ;

    Iterator<ModelFamily> iterator = modelFamilyList.iterator();

    while (iterator.hasNext()) {
        ModelFamily modelFamily = (ModelFamily)iterator.next();
        Long crisisID = modelFamily.getCollection().getCrisisId();
        Long attributeID = modelFamily.getNominalAttribute().getNominalAttributeId();
        Collection crisis = modelFamily.getCollection();
        if(crisis.isMicromapperEnabled())
        {
        	CrisisNominalAttributeModel temp = new CrisisNominalAttributeModel(crisisID, attributeID);
        	if(!findDuplicate(crisisNominalAttributeModelList, temp)) {
        		crisisNominalAttributeModelList.add(temp);
        	}
        }
    }
    return crisisNominalAttributeModelList;
}
 
Example #19
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<SimplePageLogEntry> getStudentPageLogEntries(long itemId, String userId) {		
	DetachedCriteria d = DetachedCriteria.forClass(SimplePageLogEntry.class).add(Restrictions.eq("userId", userId))
			.add(Restrictions.eq("itemId", itemId))
			.add(Restrictions.isNotNull("studentPageId"));

	return (List<SimplePageLogEntry>) getHibernateTemplate().findByCriteria(d);
}
 
Example #20
Source File: ECRFStatusEntryDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected long handleGetCount(Long probandListEntryId, Long ecrfId, Long ecrfStatusTypeId, Boolean valueLockdown, Boolean done, Boolean validated,
		Boolean review, Boolean verified)
		throws Exception {
	org.hibernate.Criteria ecrfStatusEntryCriteria = createEcrfStatusEntryCriteria();
	if (probandListEntryId != null) {
		ecrfStatusEntryCriteria.add(Restrictions.eq("listEntry.id", probandListEntryId.longValue()));
	}
	if (ecrfId != null) {
		ecrfStatusEntryCriteria.add(Restrictions.eq("ecrf.id", ecrfId.longValue()));
	}
	if (ecrfStatusTypeId != null || valueLockdown != null || done != null || validated != null || review != null || verified != null) {
		org.hibernate.Criteria ecrfStatusTypeCriteria = ecrfStatusEntryCriteria.createCriteria("status");
		if (ecrfStatusTypeId != null) {
			ecrfStatusTypeCriteria.add(Restrictions.idEq(ecrfStatusTypeId.longValue()));
		}
		if (valueLockdown != null) {
			ecrfStatusTypeCriteria.add(Restrictions.eq("valueLockdown", valueLockdown.booleanValue()));
		}
		if (done != null) {
			ecrfStatusTypeCriteria.add(Restrictions.eq("done", done.booleanValue()));
		}
		if (validated != null) {
			ecrfStatusTypeCriteria.add(Restrictions.eq("validated", validated.booleanValue()));
		}
		if (review != null) {
			ecrfStatusTypeCriteria.add(Restrictions.eq("review", review.booleanValue()));
		}
		if (verified != null) {
			ecrfStatusTypeCriteria.add(Restrictions.eq("verified", verified.booleanValue()));
		}
	}
	return (Long) ecrfStatusEntryCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example #21
Source File: GlossaryDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Integer wordCount(final String word, final Integer glossary_id) {
	return executeOnTransaction(new IExecuteOnTransaction<Integer>() {
		@Override
		public Integer execute(Session session) {
			if ((word != null && !word.trim().isEmpty()) || glossary_id != null) {

				Criteria c;

				if (glossary_id == null) {
					c = session.createCriteria(SbiGlWord.class, "gl_word");
				} else {
					// filter by glossary
					c = session.createCriteria(SbiGlWlist.class, "wlist");
					c.createAlias("wlist.word", "gl_word");
					c.createAlias("wlist.content", "gl_cont");
					c.add(Restrictions.eq("gl_cont.glossaryId", glossary_id));
				}

				if (word != null && !word.isEmpty()) {
					c.add(Restrictions.like("gl_word.word", word, MatchMode.ANYWHERE).ignoreCase());
				}

				c.setProjection(Projections.rowCount());

				return ((Long) c.uniqueResult()).intValue();

			}

			return ((Long) session.createCriteria(SbiGlWord.class).setProjection(Projections.rowCount()).uniqueResult()).intValue();

		}

	});
}
 
Example #22
Source File: ChannelFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * List all vendor content sources (org is null)
 * @return list of vendor content sources
 */
@SuppressWarnings("unchecked")
public static List<ContentSource> listVendorContentSources() {
    Criteria criteria = getSession().createCriteria(ContentSource.class);
    criteria.add(Restrictions.isNull("org"));
    return criteria.list();
}
 
Example #23
Source File: DutyRosterTurnDaoImpl.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<String> handleFindTitles(Long trialDepartmentId,
		Long staffId, Long trialId, String titleInfix, Integer limit)
		throws Exception {
	Criteria dutyRosterCriteria = createDutyRosterTurnCriteria("dutyRosterTurn");
	Criteria trialCriteria = null;
	if (trialDepartmentId != null) {
		trialCriteria = dutyRosterCriteria.createCriteria("trial", CriteriaSpecification.LEFT_JOIN);
	} else if (trialId != null) {
		trialCriteria = dutyRosterCriteria.createCriteria("trial", CriteriaSpecification.INNER_JOIN);
	}
	if (trialDepartmentId != null || trialId != null) {
		if (trialDepartmentId != null) {
			trialCriteria.add(Restrictions.or(Restrictions.isNull("dutyRosterTurn.trial"), Restrictions.eq("department.id", trialDepartmentId.longValue())));
		}
		if (trialId != null) {
			trialCriteria.add(Restrictions.idEq(trialId.longValue()));
		}
	}
	if (staffId != null) {
		dutyRosterCriteria.add(Restrictions.eq("staff.id", staffId.longValue()));
	}
	CategoryCriterion.apply(dutyRosterCriteria, new CategoryCriterion(titleInfix, "title", MatchMode.ANYWHERE));
	dutyRosterCriteria.addOrder(Order.asc("title"));
	dutyRosterCriteria.setProjection(Projections.distinct(Projections.property("title")));
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.DUTY_ROSTER_TURN_TITLE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.DUTY_ROSTER_TURN_TITLE_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), dutyRosterCriteria);
	return dutyRosterCriteria.list();
}
 
Example #24
Source File: CriteriaVisitor.java    From geomajas-project-server with GNU Affero General Public License v3.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object visit(After after, Object extraData) {
	String propertyName = getPropertyName(after.getExpression1());
	String finalName = parsePropertyName(propertyName, after);
	Object literal = getLiteralValue(after.getExpression2());
	if (literal instanceof Date) {
		return Restrictions.gt(finalName, literal);
	} else {
		throw new UnsupportedOperationException("visit(Object userData)");
	}
}
 
Example #25
Source File: HibernateDao.java    From DWSurvey with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 按属性条件参数创建Criterion,辅助函数.
 */
protected Criterion buildCriterion(final String propertyName, final Object propertyValue, final MatchType matchType) {
	AssertUtils.hasText(propertyName, "propertyName不能为空");
	Criterion criterion = null;
	//根据MatchType构造criterion
	switch (matchType) {
	case EQ:
		criterion = Restrictions.eq(propertyName, propertyValue);
		break;
	case LIKE:
		criterion = Restrictions.like(propertyName, (String) propertyValue, MatchMode.ANYWHERE);
		break;

	case LE:
		criterion = Restrictions.le(propertyName, propertyValue);
		break;
	case LT:
		criterion = Restrictions.lt(propertyName, propertyValue);
		break;
	case GE:
		criterion = Restrictions.ge(propertyName, propertyValue);
		break;
	case GT:
		criterion = Restrictions.gt(propertyName, propertyValue);
		break;
	case NE:
		criterion = Restrictions.ne(propertyName, propertyValue);
	}
	return criterion;
}
 
Example #26
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public SimpleStudentPage findStudentPage(long itemId, Collection<String> groups) {
	if (groups == null || groups.size() == 0) // no possible groups, so no result
	    return null;

	DetachedCriteria d = DetachedCriteria.forClass(SimpleStudentPage.class).add(Restrictions.eq("itemId", itemId))
		.add(Restrictions.in("group", groups)).add(Restrictions.eq("deleted", false));
	List<SimpleStudentPage> list = (List<SimpleStudentPage>) getHibernateTemplate().findByCriteria(d);
	
	if(list.size() > 0) {
		return list.get(0);
	}else {
		return null;
	}
}
 
Example #27
Source File: HibernateUtil.java    From SensorWebClient with GNU General Public License v2.0 5 votes vote down vote up
public static void deactivateSubscription(final String subscriptionID, final String userID) {
    execute(new CriteriaExecution<Void>() {
        @Override
        public Void execute(final Session session) {
            Criteria criteria = session.createCriteria(Subscription.class);
            criteria.add(Restrictions.and(Restrictions.eq(USER_ID, Integer.valueOf(userID)),
                                          Restrictions.eq(SUBSCRIPTION_ID, subscriptionID)));
            Subscription subscription = (Subscription) criteria.uniqueResult();
            subscription.setActive(false);
            session.update(subscription);
            return null;
        }
    });
}
 
Example #28
Source File: TaskQueueDaoImpl.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void deleteTaskQueue(Long taskQueueID) {
    List<TaskQueue> taskQueues = findByCriteria(Restrictions.eq("taskQueueID", taskQueueID));
    if(taskQueues.size() > 0){
        delete(taskQueues.get(0));
    }
    //To change body of implemented methods use File | Settings | File Templates.
}
 
Example #29
Source File: SimplePageToolDaoImpl.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public List<SimplePageItem> findTopLevelPageItemsBySakaiIds(List<String> ids) {
	DetachedCriteria d = DetachedCriteria.forClass(SimplePageItem.class)
		.add(Restrictions.in("sakaiId", ids))
		.add(Restrictions.eq("pageId", 0L))
		.add(Restrictions.eq("type",SimplePageItem.PAGE));

	List<SimplePageItem> list = (List<SimplePageItem>) getHibernateTemplate().findByCriteria(d);

	if (list == null || list.size() < 1) {
		return null;
	}

	return list;
}
 
Example #30
Source File: VirtualHostManagerFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @param identifier node identifier
 * @return the node with the given identifier or null
 */
public Optional<VirtualHostManagerNodeInfo> lookupNodeInfoByIdentifier(
        String identifier) {
    VirtualHostManagerNodeInfo result = (VirtualHostManagerNodeInfo) getSession()
            .createCriteria(VirtualHostManagerNodeInfo.class)
            .add(Restrictions.eq("identifier", identifier))
            .uniqueResult();

    return Optional.ofNullable(result);
}