Java Code Examples for org.hibernate.criterion.Restrictions

The following examples show how to use org.hibernate.criterion.Restrictions. These examples are extracted from open source projects. 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 Project: gocd   Source File: AccessTokenSqlMapDao.java    License: 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 2
Source Project: ctsms   Source File: CriteriaUtil.java    License: 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 3
@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 4
Source Project: onedev   Source File: DefaultIssueManager.java    License: 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 5
@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 6
Source Project: sakai   Source File: BullhornServiceImpl.java    License: 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
@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 8
@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 9
Source Project: mamute   Source File: QuestionDAO.java    License: 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 10
Source Project: ctsms   Source File: InquiryDaoImpl.java    License: 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 11
@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 12
@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 13
@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 14
Source Project: webcurator   Source File: InTrayDAOImpl.java    License: 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 15
@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 16
@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 17
@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 18
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 19
@SuppressWarnings("unchecked")
public static List<BasicRule> getAllOtherBasicRules(String userID) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(BasicRule.class);
    Criterion restriction = Restrictions.not(Restrictions.eq(OWNER_ID, Integer.valueOf(userID)));
    List<BasicRule> rules = crit.add(restriction).list();
    session.getTransaction().commit();
    return rules;
}
 
Example 20
Source Project: Spring-MVC-Blueprints   Source File: LoginDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public Set<String> getUserRoles(int id) {
	Set<String> roleNames = new HashSet<>();
	Session session = this.sessionFactory.getCurrentSession();
	Criteria crit = session.createCriteria(RolePermission.class);
	crit.add(Restrictions.like("login.id", id));
	List<RolePermission> permissionRoles = crit.list();

	for (RolePermission rp : permissionRoles) {
		roleNames.add(rp.getRole().getName());
	}
	return roleNames;
}
 
Example 21
Source Project: webcurator   Source File: TargetInstanceDAOImpl.java    License: Apache License 2.0 5 votes vote down vote up
public int countActiveTIsForTarget(final Long targetOid) {
	return (Integer) getHibernateTemplate().execute(
		new HibernateCallback() {
			public Object doInHibernate(Session session) {					
				Criteria query = session.createCriteria(TargetInstance.class);
				query.setProjection(Projections.rowCount());
									
				Disjunction stateDisjunction = Restrictions.disjunction();
				
				stateDisjunction.add(Restrictions.eq("state", TargetInstance.STATE_SCHEDULED));
				stateDisjunction.add(Restrictions.eq("state", TargetInstance.STATE_QUEUED));
				stateDisjunction.add(Restrictions.eq("state", TargetInstance.STATE_RUNNING));
				stateDisjunction.add(Restrictions.eq("state", TargetInstance.STATE_PAUSED));
				stateDisjunction.add(Restrictions.eq("state", TargetInstance.STATE_STOPPING));

				query.add(stateDisjunction);
				
				//query.createAlias("target", "t");
				query.createCriteria("target").add(Restrictions.eq("oid", targetOid));

				Integer count = (Integer) query.uniqueResult();
                
                return count;
			}
		}
	);	
}
 
Example 22
Source Project: Mall-Server   Source File: GoodsCommentDaoImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<GoodsComment> findByGoodsIdAndPage(int goodsId, int page, int pageSize) {
    DetachedCriteria criteria = DetachedCriteria.forClass(GoodsComment.class);

    criteria.add(Restrictions.eq("goodsid", goodsId));
    int offset = (page - 1) * pageSize;
    return (List<GoodsComment>) template.findByCriteria(criteria, offset, pageSize);
}
 
Example 23
public boolean isAssignmentDefined(final Long gradableObjectId) {
    final HibernateCallback<Number> hc = session -> (Number) session.createCriteria(GradebookAssignment.class)
                .add(Restrictions.eq("id", gradableObjectId))
                .add(Restrictions.eq("removed", false))
                .setProjection(Projections.rowCount())
                .uniqueResult();
    return getHibernateTemplate().execute(hc).intValue() == 1;
}
 
Example 24
public List<TaskTranslation> findAllTranslationsByClientAppIdAndStatus(Long clientAppId, String status, Integer count) {
    Map map = new HashMap();
    map.put("clientAppId", clientAppId);
    map.put("status", status);
    List<TaskTranslation> list = findByCriteria(Restrictions.allEq(map), count);
    return list;
}
 
Example 25
Source Project: onedev   Source File: DefaultPullRequestManager.java    License: MIT License 5 votes vote down vote up
@Transactional
@Listen
public void on(RefUpdated event) {
	String branch = GitUtils.ref2branch(event.getRefName());
	if (branch != null && !event.getOldCommitId().equals(ObjectId.zeroId())) {
		ProjectAndBranch projectAndBranch = new ProjectAndBranch(event.getProject(), branch);
		Criterion criterion = Restrictions.and(
				ofOpen(), 
				Restrictions.or(ofSource(projectAndBranch), ofTarget(projectAndBranch)));
		checkAsync(query(EntityCriteria.of(PullRequest.class).add(criterion)));
	}
}
 
Example 26
Source Project: TinyMooc   Source File: CourseController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 管理课程
 *
 * @param req
 * @param res
 * @return
 */
@RequestMapping("manageCoursePage.htm")
public ModelAndView manageCoursePage(HttpServletRequest req, HttpServletResponse res) {
    String courseId = ServletRequestUtils.getStringParameter(req, "courseId", "");
    Course course = courseService.findById(Course.class, courseId);
    DetachedCriteria detachedCriteria = DetachedCriteria.forClass(DataDic.class)
            .add(Restrictions.eq("dicKey", "专业分类"));
    List<DataDic> dataDicList = (List<DataDic>) courseService.queryAllOfCondition(DataDic.class, detachedCriteria);

    req.setAttribute("course", course);
    req.setAttribute("dataDicList", dataDicList);
    return new ModelAndView("/course/manageCourse");
}
 
Example 27
Source Project: Spring-MVC-Blueprints   Source File: LoginDaoImpl.java    License: MIT License 5 votes vote down vote up
@Transactional
@SuppressWarnings("unchecked")
@Override
public List<HrmsLogin> getEmployeeUsers() {
	Session session = this.sessionFactory.getCurrentSession();
	Criteria crit = session.createCriteria(HrmsLogin.class);
	crit.add(Restrictions.like("role","employee"));

	List<HrmsLogin> users = crit.list();
	
	return users;
}
 
Example 28
Source Project: TinyMooc   Source File: FavoriteController.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@RequestMapping("myFavorite.htm")
public ModelAndView myFavotite(HttpServletRequest req, HttpServletResponse res) throws MarsException {
    User user = (User) req.getSession().getAttribute("user");
    DetachedCriteria dCriteria = DetachedCriteria.forClass(Favorite.class)
            .add(Restrictions.eq("user", user));

    int pageSize = 5;
    int totalPage = favoriteService.countTotalPage(dCriteria, pageSize);
    PageHelper.forPage(totalPage, pageSize);
    List<Favorite> favorites = (List<Favorite>) favoriteService.getByPage(dCriteria, pageSize);
    req.setAttribute("favorites", favorites);
    return new ModelAndView("/favorite/myFavorite");
}
 
Example 29
@Override
public Reference get(Reference reference) {
    final Criteria crit = sessionService.getSession().createCriteria(Reference.class);

    if (StringUtils.isEmpty(reference.getSections())) {
        crit.add(Restrictions.isNull("sections"));
    } else {
        crit.add(Restrictions.eq("sections", reference.getSections()));
    }

    crit.createAlias("requirement", "req");
    crit.add(Restrictions.eq("req.name", reference.getRequirement().getName()));
    crit.createAlias("req.repository", "reqRepo");
    crit.add(Restrictions.eq("reqRepo.uid", reference.getRequirement().getRepository().getUid()));
    crit.createAlias("specification", "spec");
    crit.add(Restrictions.eq("spec.name", reference.getSpecification().getName()));
    crit.createAlias("spec.repository", "specRepo");
    crit.add(Restrictions.eq("specRepo.uid", reference.getSpecification().getRepository().getUid()));
    crit.createAlias(SYSTEM_UNDER_TEST, SUT);
    crit.add(Restrictions.eq(SUT_NAME, reference.getSystemUnderTest().getName()));
    crit.createAlias("sut.project", "sp");
    crit.add(Restrictions.eq("sp.name", reference.getSystemUnderTest().getProject().getName()));

    Reference result = ( Reference ) crit.uniqueResult();
    HibernateLazyInitializer.init(result);
    return result;
}
 
Example 30
@Deprecated
@SuppressWarnings("unchecked")
public static List<ComplexRule> searchComplex(String row, String text) {
    text = "%" + text + "%";
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(ComplexRule.class);
    List<ComplexRule> rules = crit.add(Restrictions.and(Restrictions.eq(PUBLISHED, true),
                                                        Restrictions.ilike(row, text))).list();
    session.getTransaction().commit();
    return rules;
}