Java Code Examples for org.hibernate.criterion.Restrictions

The following are top voted examples for showing how to use org.hibernate.criterion.Restrictions. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: dhus-core   File: NetworkUsageDao.java   Source Code and License 8 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 2
Project: hska-vis-legacy   File: UserDAO.java   Source Code and License 8 votes vote down vote up
public User getUserByUsername(String name) {
	SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
	Session session = sessionFactory.getCurrentSession();
	try
	{
		User user = null;
		session.beginTransaction();
           Criteria crit = session.createCriteria(User.class);
           crit.add(Restrictions.eq("username",name));
           List<User> resultList = crit.list();
           if (resultList.size() > 0) {
           	user = (User) crit.list().get(0);
           }
           session.getTransaction().commit();
           return user;
	}
	catch (HibernateException e)
	{
		System.out.println("Hibernate Exception" + e.getMessage());
		session.getTransaction().rollback();
		throw new RuntimeException(e);
	}
}
 
Example 3
Project: DWSurvey   File: SurveyDirectoryManagerImpl.java   Source Code and License 6 votes vote down vote up
@Override
public Page<SurveyDirectory> findPage(Page<SurveyDirectory> page,
		SurveyDirectory entity) {
	page.setOrderBy("createDate");
	page.setOrderDir("desc");
	
	List<Criterion> criterions=new ArrayList<Criterion>();
	criterions.add(Restrictions.eq("visibility", 1));
	criterions.add(Restrictions.eq("surveyState", 1));
	
	criterions.add(Restrictions.eq("dirType", 2));
	criterions.add(Restrictions.eq("surveyModel", 1));
	
	Integer share = entity.getIsShare();
	if(share!=null && share==1){
		criterions.add(Restrictions.eq("isShare", share));
	}

	return surveyDirectoryDao.findPageList(page, criterions);
}
 
Example 4
Project: bdf2   File: HibernateDao.java   Source Code and License 6 votes vote down vote up
private void buildCriterions(Collection<com.bstek.dorado.data.provider.Criterion> criterions,
		org.hibernate.criterion.Junction dc) {
	for (com.bstek.dorado.data.provider.Criterion c : criterions) {
		if (c instanceof SingleValueFilterCriterion) {
			SingleValueFilterCriterion fc = (SingleValueFilterCriterion) c;
			dc.add(this.buildCriterion(fc));
		}
		if (c instanceof Junction) {
			Junction jun = (Junction) c;
			org.hibernate.criterion.Junction junction = null;
			if (jun instanceof Or) {
				junction = Restrictions.disjunction();
			} else if (jun instanceof And) {
				junction = Restrictions.conjunction();
			}
			Collection<com.bstek.dorado.data.provider.Criterion> subCriterions = jun.getCriterions();
			if (subCriterions != null) {
				buildCriterions(subCriterions, dc);
			}
			dc.add(junction);
		}
	}
}
 
Example 5
Project: ctsms   File: ECRFDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected long handleGetCount(Long trialId, Long groupId, Long visitId, Boolean active) throws Exception {
	org.hibernate.Criteria ecrfCriteria = createEcrfCriteria(null);
	if (trialId != null) {
		ecrfCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (groupId != null) {
		ecrfCriteria.add(Restrictions.or(Restrictions.eq("group.id", groupId.longValue()),
				Restrictions.isNull("group.id")));
	}
	if (visitId != null) {
		ecrfCriteria.add(Restrictions.or(Restrictions.eq("visit.id", visitId.longValue()),
				Restrictions.isNull("visit.id")));
	}
	if (active != null) {
		ecrfCriteria.add(Restrictions.eq("active", active.booleanValue()));
	}
	return (Long) ecrfCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example 6
Project: ImageClassify   File: ZipService.java   Source Code and License 6 votes vote down vote up
/**
	 * 展示已经解压未识别的列表
	 */
@Override
public List<Zip> showZipAndUnClassifyFolder() {
	List<Zip> zips = new ArrayList<Zip>();
       Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx = session.beginTransaction();//生成事务实例  
	 try {
		  zips = session.createCriteria(Zip.class).add(Restrictions.eq("isZip", 1)).add(Restrictions.eq("isClassify", 0)).list();
		  tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	 return zips;
}
 
Example 7
Project: ctsms   File: TrialDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<Trial> handleFindByDepartmentPayoffs(Long departmentId, Boolean payoffs, PSFVO psf) throws Exception {
	org.hibernate.Criteria trialCriteria = createTrialCriteria(null);
	SubCriteriaMap criteriaMap = new SubCriteriaMap(Trial.class, trialCriteria);
	if (departmentId != null) {
		trialCriteria.add(Restrictions.eq("department.id", departmentId.longValue()));
	}
	if (payoffs != null) {
		if (payoffs) {
			trialCriteria.add(Restrictions.sizeGt("payoffs", 0));
		} else {
			trialCriteria.add(Restrictions.sizeEq("payoffs", 0));
		}
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return trialCriteria.list();
}
 
Example 8
Project: ctsms   File: StaffTagDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<StaffTag> handleFindByPersonOrganisationIdExcel(
		Boolean person, Boolean organisation, Long tagId, Boolean excel) throws Exception {
	org.hibernate.Criteria staffTagCriteria = this.getSession().createCriteria(StaffTag.class);
	staffTagCriteria.setCacheable(true);
	if (excel != null) {
		staffTagCriteria.add(Restrictions.eq("excel", excel.booleanValue()));
	}
	if (person != null) {
		if (tagId != null) {
			staffTagCriteria.add(Restrictions.or(Restrictions.eq("person", person.booleanValue()), Restrictions.idEq(tagId.longValue())));
		} else {
			staffTagCriteria.add(Restrictions.eq("person", person.booleanValue()));
		}
	}
	if (organisation != null) {
		if (tagId != null) {
			staffTagCriteria.add(Restrictions.or(Restrictions.eq("organisation", organisation.booleanValue()), Restrictions.idEq(tagId.longValue())));
		} else {
			staffTagCriteria.add(Restrictions.eq("organisation", organisation.booleanValue()));
		}
	}
	return staffTagCriteria.list();
}
 
Example 9
Project: ctsms   File: ProbandListEntryTagDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<ProbandListEntryTag> handleFindByTrialExcelEcrfProbandSorted(Long trialId, Boolean excel, Boolean ecrf, Long probandId) throws Exception {
	org.hibernate.Criteria listEntryTagCriteria = createListEntryTagCriteria();
	if (trialId != null) {
		listEntryTagCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (excel != null) {
		listEntryTagCriteria.add(Restrictions.or(Restrictions.eq("excelValue", excel.booleanValue()),
				Restrictions.eq("excelDate", excel.booleanValue())));
	}
	if (ecrf != null) {
		listEntryTagCriteria.add(Restrictions.eq("ecrfValue", ecrf.booleanValue()));
	}
	if (probandId != null) {
		listEntryTagCriteria.createCriteria("tagValues", CriteriaSpecification.INNER_JOIN).createCriteria("listEntry", CriteriaSpecification.INNER_JOIN)
		.add(Restrictions.eq("proband.id", probandId.longValue()));
	}
	applySortOrders(listEntryTagCriteria);
	// listEntryTagCriteria.setResultTransformer(org.hibernate.Criteria.DISTINCT_ROOT_ENTITY);
	// return listEntryTagCriteria.list();
	return CriteriaUtil.listDistinctRoot(listEntryTagCriteria, this, "trial.id", "position");
}
 
Example 10
Project: ctsms   File: CriteriaDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<Criteria> handleFindByModuleCategory(DBModule module,
		String category, Boolean loadByDefault, PSFVO psf) throws Exception {
	org.hibernate.Criteria criteriaCriteria = createCriteriaCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(Criteria.class, criteriaCriteria);
	if (module != null) {
		criteriaCriteria.add(Restrictions.eq("module", module));
	}
	if (loadByDefault != null) {
		criteriaCriteria.add(Restrictions.eq("loadByDefault", loadByDefault.booleanValue()));
	}
	if (category != null && category.length() > 0) {
		criteriaCriteria.add(Restrictions.eq("category", category));
	} else {
		criteriaCriteria.add(Restrictions.or(Restrictions.eq("category", ""), Restrictions.isNull("category")));
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return criteriaCriteria.list();
}
 
Example 11
Project: bdf2   File: HibernateDao.java   Source Code and License 6 votes vote down vote up
private void buildCriterions(Collection<com.bstek.dorado.data.provider.Criterion> criterions,DetachedCriteria dc){
	for(com.bstek.dorado.data.provider.Criterion c : criterions){
		if (c instanceof SingleValueFilterCriterion){
			SingleValueFilterCriterion fc = (SingleValueFilterCriterion) c;
			dc.add(this.buildCriterion(fc));
		}
		if (c instanceof Junction) {
			Junction jun = (Junction) c;
			org.hibernate.criterion.Junction junction = null;
			if (jun instanceof Or) {
				junction = Restrictions.disjunction();
			} else if (jun instanceof And) {
				junction = Restrictions.conjunction();
			}
			Collection<com.bstek.dorado.data.provider.Criterion> subCriterions = jun.getCriterions();
			if (subCriterions != null) {
				buildCriterions(subCriterions, junction);
			}
			dc.add(junction);
		}
	}
}
 
Example 12
Project: gitplex-mit   File: DefaultPullRequestReferenceManager.java   Source Code and License 6 votes vote down vote up
@Transactional
@Listen
public void on(PullRequestEvent event) {
	if (event instanceof MarkdownAware) {
		String markdown = ((MarkdownAware)event).getMarkdown();
		if (markdown != null) {
			String html = markdownManager.render(markdown, null, false);
			
			for (PullRequest referenced: new PullRequestParser().parseRequests(html)) {
				if (!referenced.equals(event.getRequest())) {
					EntityCriteria<PullRequestReference> criteria = EntityCriteria.of(PullRequestReference.class);
					criteria.add(Restrictions.eq("referenced", referenced));
					criteria.add(Restrictions.eq("referencedBy", event.getRequest()));
					if (dao.find(criteria) == null) {
						PullRequestReference reference = new PullRequestReference();
						reference.setReferencedBy(event.getRequest());
						reference.setReferenced(referenced);
						reference.setDate(new Date());
						reference.setUser(userManager.getCurrent());
						save(reference);
					}
				}					
			}
		}
	}
}
 
Example 13
Project: ctsms   File: ProbandListEntryTagDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<ProbandListEntryTag> handleFindAllSorted(String nameInfix, Integer limit) throws Exception {
	org.hibernate.Criteria listEntryTagCriteria = createListEntryTagCriteria();
	if (!CommonUtil.isEmptyString(nameInfix)) {
		org.hibernate.Criteria trialCriteria = listEntryTagCriteria.createCriteria("trial", "trial0", CriteriaSpecification.INNER_JOIN);
		org.hibernate.Criteria fieldCriteria = listEntryTagCriteria.createCriteria("field", "inputField", CriteriaSpecification.INNER_JOIN);
		//fieldCriteria.add(Restrictions.eq("localized", false));
		listEntryTagCriteria.add(Restrictions.or(
				(new CategoryCriterion(nameInfix, "inputField.nameL10nKey", MatchMode.ANYWHERE)).getRestriction(),
				(new CategoryCriterion(nameInfix, "trial0.name", MatchMode.ANYWHERE)).getRestriction()
				));
	}
	applySortOrders(listEntryTagCriteria);
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.PROBAND_LIST_ENTRY_TAG_FIELD_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.PROBAND_LIST_ENTRY_TAG_FIELD_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), listEntryTagCriteria);
	return listEntryTagCriteria.list();
}
 
Example 14
Project: sjk   File: AppDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<App> getLatest(short catalog, Integer subCatalog, Long date, int currentPage, int pageSize,
        Boolean noAds, Boolean noVirus, Boolean official) {
    Criteria cri = getSession().createCriteria(App.class);
    getLastestByFilter(catalog, subCatalog, date, cri);
    cri.add(Restrictions.eq("hidden", false));
    filterAdVirusOfficial(noAds, noVirus, official, cri);

    if (date != null) {
        cri.addOrder(Order.desc("viewCount"));
    } else {
        // 不查询日期,按日期先排序.
        cri.addOrder(Order.desc("lastUpdateTime"));
    }
    cri.setFirstResult(HibernateHelper.firstResult(currentPage, pageSize));
    cri.setMaxResults(pageSize);
    List<App> list = HibernateHelper.list(cri);
    return list;
}
 
Example 15
Project: Equella   File: EntityLockingServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Transactional
public EntityLock lockEntity(BaseEntity entity, String sessionId)
{
	EntityLock lock = entityLockDao.findByCriteria(Restrictions.eq("entity", entity));
	if( lock != null )
	{
		throw new LockedException("Entity is already locked", lock.getUserID(), lock.getUserSession(),
			entity.getId());
	}
	else
	{
		lock = new EntityLock();
		lock.setEntity(entity);
		lock.setUserID(CurrentUser.getUserID());
		lock.setUserSession(sessionId);
		lock.setInstitution(CurrentInstitution.get());
		entityLockDao.save(lock);
		return lock;
	}
}
 
Example 16
Project: Equella   File: EntityLockingServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Transactional(propagation = Propagation.MANDATORY)
public EntityLock getLock(BaseEntity entity, String lockId)
{
	EntityLock lock = entityLockDao.findByCriteria(Restrictions.eq("entity", entity));
	if( lock != null )
	{
		if( lockId == null )
		{
			throw new LockedException("Entity is locked by another user '" + lock.getUserID() + "'",
				lock.getUserID(), lock.getUserSession(), entity.getId());
		}
		if( !lockId.equals(lock.getUserSession()) )
		{
			throw new LockedException("Wrong lock id. Entity is locked by user.", lock.getUserID(),
				lock.getUserSession(), entity.getId());
		}
	}
	else if( lockId != null )
	{
		throw new LockedException("Entity is not locked", null, null, entity.getId());
	}
	return lock;
}
 
Example 17
Project: ImageClassify   File: OauthService.java   Source Code and License 6 votes vote down vote up
/**
 * 依据oauth_token找到oauth实体对象
 */
@Override
public Oauth findOauthByOauthToken(String oauth_token) {
	 Oauth oauth = null;
	 Session session = HibernateUtils.getSession();
	 Transaction tx = session.beginTransaction(); //开启事务
	 try {
		 //使用criteria查询oauth对象
		  oauth = (Oauth) session.createCriteria(Oauth.class).add(Restrictions.eq("oauth_token", oauth_token)).uniqueResult();
		  tx.commit();
	} catch (Exception e) {
	  e.printStackTrace();
	  tx.rollback();
	}finally{
		HibernateUtils.closeSession();
	}
	 return oauth; //返回oauth对象
}
 
Example 18
Project: ctsms   File: InquiryValueDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected long handleGetCount(Long trialId, String category, Boolean active, Boolean activeSignup, Long probandId) throws Exception {
	org.hibernate.Criteria inquiryValueCriteria = createInquiryValueCriteria();
	if (probandId != null) {
		inquiryValueCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
	}
	org.hibernate.Criteria inquiryCriteria = inquiryValueCriteria.createCriteria("inquiry", CriteriaSpecification.INNER_JOIN);
	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()));
	}
	if (category != null && category.length() > 0) {
		inquiryCriteria.add(Restrictions.eq("category", category));
	} else {
		inquiryCriteria.add(Restrictions.or(Restrictions.eq("category", ""), Restrictions.isNull("category")));
	}
	return (Long) inquiryValueCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example 19
Project: Equella   File: PortletServiceImpl.java   Source Code and License 6 votes vote down vote up
@Override
@Transactional
public void userDeletedEvent(UserDeletedEvent event)
{
	Criterion owner = Restrictions.eq("owner", event.getUserID());
	Criterion inst = Restrictions.eq("institution", CurrentInstitution.get());
	for( Portlet p : portletDao.findAllByCriteria(owner, inst) )
	{
		delete(p, false);
	}

	prefDao.deleteAllForUser(event.getUserID());

	// We don't want to call super here since we're deleting the portlets.
	// The default behaviour for base entities is to orphan them instead
	//
	// super.userDeletedEvent(event);
}
 
Example 20
Project: ctsms   File: InventoryBookingDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
protected Collection<InventoryBooking> handleFindByCourseSorted(Long courseId, Boolean isRelevantForCourseAppointments, boolean sort) throws Exception
{
	Criteria bookingCriteria = createBookingCriteria();
	if (courseId != null) {
		bookingCriteria.add(Restrictions.eq("course.id", courseId.longValue()));
	}
	if (isRelevantForCourseAppointments != null) {
		bookingCriteria.createCriteria("inventory", CriteriaSpecification.INNER_JOIN).createCriteria("category", CriteriaSpecification.INNER_JOIN)
		.add(Restrictions.eq("relevantForCourseAppointments", isRelevantForCourseAppointments.booleanValue()));
	}
	if (sort) {
		bookingCriteria.addOrder(Order.asc("start"));
	}
	return bookingCriteria.list();
}
 
Example 21
Project: Equella   File: OAuthServiceImpl.java   Source Code and License 6 votes vote down vote up
@Transactional
@Override
public void userDeletedEvent(UserDeletedEvent event)
{
	// The super behaviour is to orphan things and we want most OAuthClients
	// to stick around, so let owned ones be orphaned first.
	super.userDeletedEvent(event);

	// ...but, clients that are locked to the user being deleted are
	// useless, so we'll delete those.
	Criterion c1 = Restrictions.eq("userId", event.getUserID());
	Criterion c2 = Restrictions.eq("institution", CurrentInstitution.get());
	for( OAuthClient oc : clientDao.findAllByCriteria(c1, c2) )
	{
		delete(oc, false);
	}

	tokenDao.deleteAllForUser(event.getUserID());
}
 
Example 22
Project: sjk   File: AppDaoImpl.java   Source Code and License 6 votes vote down vote up
@Override
public List<App> search(Short catalog, Integer subCatalog, int page, int rows, String keywords, Integer id,
        String sort, String order) {
    Criteria cri = searchByFilter(catalog, subCatalog, keywords, id);
    if (subCatalog != null) {
        cri.add(Restrictions.eq("subCatalog", subCatalog));
    }
    // cri.addOrder(Order.asc("auditCatalog"));
    if (sort != null && !sort.isEmpty()) {
        HibernateHelper.addOrder(cri, sort, order);
    } else {
        if (order != null && "asc".equals(order)) {
            cri.addOrder(Order.asc("downloadRank"));
        } else {
            cri.addOrder(Order.desc("downloadRank"));
        }
    }
    if ("marketName".equals(sort)) {
        cri.addOrder(Order.desc("downloadRank"));
    }
    // cri.addOrder(Order.asc("name"));
    cri.setMaxResults(rows);
    cri.setFirstResult(HibernateHelper.firstResult(page, rows));
    List<App> list = HibernateHelper.list(cri);
    return list;
}
 
Example 23
Project: bdf2   File: HibernateDao.java   Source Code and License 6 votes vote down vote up
private void buildCriterions(Collection<com.bstek.dorado.data.provider.Criterion> criterions,
		org.hibernate.criterion.Junction dc) {
	for (com.bstek.dorado.data.provider.Criterion c : criterions) {
		if (c instanceof SingleValueFilterCriterion) {
			SingleValueFilterCriterion fc = (SingleValueFilterCriterion) c;
			dc.add(this.buildCriterion(fc));
		}
		if (c instanceof Junction) {
			Junction jun = (Junction) c;
			org.hibernate.criterion.Junction junction = null;
			if (jun instanceof Or) {
				junction = Restrictions.disjunction();
			} else if (jun instanceof And) {
				junction = Restrictions.conjunction();
			}
			Collection<com.bstek.dorado.data.provider.Criterion> subCriterions = jun.getCriterions();
			if (subCriterions != null) {
				buildCriterions(subCriterions, dc);
			}
			dc.add(junction);
		}
	}
}
 
Example 24
Project: ctsms   File: ProbandListEntryTagDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected Collection<ProbandListEntryTag> handleFindByTrialJsVariableName(
		Long trialId, String jsVariableName) throws Exception {
	org.hibernate.Criteria listEntryTagCriteria = createListEntryTagCriteria();
	if (trialId != null) {
		listEntryTagCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	listEntryTagCriteria.add(Restrictions.eq("jsVariableName", jsVariableName));
	return listEntryTagCriteria.list();
}
 
Example 25
Project: ctsms   File: InventoryBookingDaoImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
protected Collection<InventoryBooking> handleFindByCourse(Long courseId, PSFVO psf) throws Exception
{
	Criteria bookingCriteria = createBookingCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(InventoryBooking.class, bookingCriteria);
	if (courseId != null) {
		bookingCriteria.add(Restrictions.eq("course.id", courseId.longValue()));
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return bookingCriteria.list();
}
 
Example 26
Project: Biliomi   File: CommandHistoryRecordDao.java   Source Code and License 5 votes vote down vote up
public List<CommandHistoryRecord> getLatestHistoryForCommand(String command) {
  return criteria()
      .add(Restrictions.eq("command", command))
      .addOrder(Order.desc("id"))
      .setMaxResults(20)
      .getList();
}
 
Example 27
Project: admin-shiro   File: AdminService.java   Source Code and License 5 votes vote down vote up
@Transactional(propagation = Propagation.REQUIRED, readOnly = true)
public AdminDO findByUserName(String userName){
    Criteria criteria = daoSupport.createCriteria(AdminDO.class);
    criteria.add(Restrictions.eq("userName", userName));
    Object o = criteria.list().get(0);
    if (Objects.nonNull(o)){
        return (AdminDO)o;
    }else {
        return null;
    }
}
 
Example 28
Project: ctsms   File: AnnouncementDaoImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
protected Announcement handleGetAnnouncement()
{
	org.hibernate.Criteria announcementCriteria = this.getSession().createCriteria(Announcement.class);
	announcementCriteria.setCacheable(true);
	announcementCriteria.add(Restrictions.eq("visible", true));
	announcementCriteria.addOrder(Order.desc("timestamp"));
	announcementCriteria.addOrder(Order.desc("id"));
	announcementCriteria.setMaxResults(1);
	return (Announcement) announcementCriteria.uniqueResult();
}
 
Example 29
Project: DWSurvey   File: QuestionBankManagerImpl.java   Source Code and License 5 votes vote down vote up
@Override
public QuestionBank findByNameUn(String id, String parentId, String bankName) {
	List<Criterion> criterions=new ArrayList<Criterion>();
	Criterion eqName=Restrictions.eq("bankName", bankName);
	Criterion eqParentId=Restrictions.eq("parentId", parentId);
	criterions.add(eqName);
	criterions.add(eqParentId);
	
	if(id!=null && !"".equals(id)){
		Criterion eqId=Restrictions.ne("id", id);	
		criterions.add(eqId);
	}
	return questionBankDao.findFirst(criterions);
}
 
Example 30
Project: ctsms   File: OpsSystCategoryDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected Collection<String> handleFindCategoryPreferredRubricLabels(
		String preferredRubricLabelInfix, Integer limit) throws Exception {
	org.hibernate.Criteria opsSystCategoryCriteria = this.getSession().createCriteria(OpsSystCategory.class);
	opsSystCategoryCriteria.setCacheable(true);
	CategoryCriterion.apply(opsSystCategoryCriteria, new CategoryCriterion(preferredRubricLabelInfix, "preferredRubricLabel", MatchMode.ANYWHERE));
	opsSystCategoryCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("preferredRubricLabel", ""), Restrictions.isNull("preferredRubricLabel"))));
	// opsSystCategoryCriteria.add(Restrictions.eq("revision",
	// Settings.getString(SettingCodes.OPS_SYSTEMATICS_REVISION, Bundle.SETTINGS, DefaultSettings.OPS_SYSTEMATICS_REVISION)));
	opsSystCategoryCriteria.addOrder(Order.asc("preferredRubricLabel"));
	opsSystCategoryCriteria.setProjection(Projections.distinct(Projections.property("preferredRubricLabel")));
	CriteriaUtil.applyLimit(limit, Settings.getIntNullable(SettingCodes.OPS_SYST_CATEGORY_PREFERRED_RUBRIC_LABEL_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS,
			DefaultSettings.OPS_SYST_CATEGORY_PREFERRED_RUBRIC_LABEL_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT), opsSystCategoryCriteria);
	return opsSystCategoryCriteria.list();
}
 
Example 31
Project: sjk   File: AppDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public App getAppByPackageName(Session sess, String pkname) {
    Criteria cri = sess.createCriteria(App.class);
    cri.add(Restrictions.eq("pkname", pkname));
    Object o = cri.uniqueResult();
    if (o != null) {
        return (App) o;
    }
    return null;
}
 
Example 32
Project: sjk   File: AppDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<App> get(List<Integer> ids, String sort, String order) {
    List<Integer> sorted = new ArrayList<Integer>(ids);
    Collections.sort(sorted);
    Criteria cri = getSession().createCriteria(App.class);
    cri.add(Restrictions.in("id", sorted));
    cri.add(Restrictions.eq("hidden", false));
    HibernateHelper.addOrder(cri, sort, order);
    List<App> list = HibernateHelper.list(cri);
    return list;
}
 
Example 33
Project: Biliomi   File: InvestmentRecordDao.java   Source Code and License 5 votes vote down vote up
public List<InvestmentRecord> getRecords(User user, int limit) {
  return criteria()
      .createAlias("invester", "i")
      .add(Restrictions.eq("i.id", user.getId()))
      .addOrder(Order.desc("id"))
      .setMaxResults(limit)
      .getList();
}
 
Example 34
Project: Biliomi   File: GameDao.java   Source Code and License 5 votes vote down vote up
public Game getBySteamIdOrName(long steamId, String name) {
  return criteria()
      .add(Restrictions.or(
          Restrictions.eq("steamId", steamId),
          Restrictions.eq("name", name).ignoreCase()
      ))
      .getResult();
}
 
Example 35
Project: Equella   File: OAuthTokenDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public OAuthToken getToken(String userId, OAuthClient client)
{
	// Tempororary hax for #6659
	List<OAuthToken> tokens = findAllByCriteria(Restrictions.eq("userId", userId),
		Restrictions.eq("client", client));
	if( !tokens.isEmpty() )
	{
		return tokens.get(0);
	}
	return null;
}
 
Example 36
Project: ctsms   File: ECRFStatusTypeDaoImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
protected Collection<ECRFStatusType> handleFindInitialStates()
{
	org.hibernate.Criteria ecrfStatusTypeCriteria = createEcrfStatusTypeCriteria();
	ecrfStatusTypeCriteria.add(Restrictions.eq("initial", true));
	ecrfStatusTypeCriteria.addOrder(Order.asc("id"));
	return ecrfStatusTypeCriteria.list();
}
 
Example 37
Project: uflo   File: GetHistoryActivitiyCommand.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<HistoryActivity> execute(Context context) {
	Criteria criteria=context.getSession().createCriteria(HistoryActivity.class);
	if(isProcessInstanceId){
		criteria.add(Restrictions.eq("rootProcessInstanceId", instanceId));
	}else{
		criteria.add(Restrictions.eq("historyProcessInstanceId", instanceId));
	}
	criteria.addOrder(Order.desc("endDate"));
	return criteria.list();
}
 
Example 38
Project: infotaf   File: ManipDao.java   Source Code and License 5 votes vote down vote up
public Manip getManip(String name){
	logger.debug("IN - name: {}", name);
	Criterion whereName = Restrictions.eq("nom", name);
	
	Manip manip = (Manip) getSession()
				.createCriteria(Manip.class)
				.add(whereName)
				.uniqueResult();
	return manip;
}
 
Example 39
Project: OSWf-OSWorkflow-fork   File: HibernateStore.java   Source Code and License 5 votes vote down vote up
private Criterion buildNested(NestedExpression nestedExpression) {
    
    Criterion full = null;

    for (int i = 0; i < nestedExpression.getExpressionCount(); i++) {
        Criterion expr;
        Expression expression = nestedExpression.getExpression(i);

        if (expression.isNested()) {
            expr = buildNested((NestedExpression) nestedExpression.getExpression(i));
        } else {
            FieldExpression sub = (FieldExpression) nestedExpression.getExpression(i);
            expr = queryComparison(sub);

            if (sub.isNegate()) {
                expr = Restrictions.not(expr);
            }
        }

        if (full == null) {
            full = expr;
        } else {
            switch (nestedExpression.getExpressionOperator()) {
            case AND:
                full = Restrictions.and(full, expr);
                break;

            case OR:
                full = Restrictions.or(full, expr);
            }
        }
    }

    return full;
}
 
Example 40
Project: ctsms   File: InputFieldSelectionSetValueDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected long handleGetCount(Long fieldId, Boolean preset) throws Exception {
	org.hibernate.Criteria selectionSetValueCriteria = createSelectionSetValueCriteria();
	if (fieldId != null) {
		selectionSetValueCriteria.add(Restrictions.eq("field.id", fieldId.longValue()));
	}
	if (preset != null) {
		selectionSetValueCriteria.add(Restrictions.eq("preset", preset.booleanValue()));
	}
	return (Long) selectionSetValueCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example 41
Project: DWSurvey   File: QuChenOptionManagerImpl.java   Source Code and License 5 votes vote down vote up
public int getOrderById(String quId){
	Criterion criterion=Restrictions.eq("quId", quId);
	QuChenOption quChenOption=quChenOptionDao.findFirst("orderById", false, criterion);
	if(quChenOption!=null){
		return quChenOption.getOrderById();
	}
	return 0;
}
 
Example 42
Project: ctsms   File: ECRFFieldStatusEntryDaoImpl.java   Source Code and License 5 votes vote down vote up
private static void applyEcrfFieldStatusEntryMaxIdSubCriteria(org.hibernate.Criteria ecrfFieldStatusEntryCriteria, org.hibernate.Criteria ecrfFieldCriteria,
		org.hibernate.Criteria probandListEntryCriteria, ECRFFieldStatusQueue queue, Long probandListEntryId, Long ecrfFieldId) {
	DetachedCriteria subQuery = createEcrfFieldStatusEntryDetachedCriteriaMaxId(ecrfFieldStatusEntryCriteria, ecrfFieldCriteria, probandListEntryCriteria, queue,
			probandListEntryId,
			ecrfFieldId);
	subQuery.add(Restrictions.or(Restrictions.isNull("index"),
			Restrictions.eqProperty("index", ecrfFieldStatusEntryCriteria.getAlias() + ".index")));
	ecrfFieldStatusEntryCriteria.add(Subqueries.propertyIn("id", subQuery));
}
 
Example 43
Project: DWSurvey   File: UserManagerImpl.java   Source Code and License 5 votes vote down vote up
public Page<User> findPage(Page<User> page, User entity) {
	List<Criterion> criterions=new ArrayList<Criterion>();
	Integer status = entity.getStatus();
	String loginName = entity.getLoginName();
	if(status!=null && !"".equals(status)){
		criterions.add(Restrictions.eq("status", status));
	}
	if(loginName!=null && !"".equals(loginName)){
		criterions.add(Restrictions.like("loginName", "%"+loginName+"%"));
	}
	return super.findPageByCri(page, criterions);
}
 
Example 44
Project: gitplex-mit   File: DefaultPullRequestManager.java   Source Code and License 5 votes vote down vote up
@Sessional
@Override
public PullRequest find(Project target, long number) {
	EntityCriteria<PullRequest> criteria = newCriteria();
	criteria.add(Restrictions.eq("targetProject", target));
	criteria.add(Restrictions.eq("number", number));
	return find(criteria);
}
 
Example 45
Project: sjk   File: AppDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<App> getByPackageName(String pkname) {
    Criteria cri = getSession().createCriteria(App.class);
    cri.add(Restrictions.eq("pkname", pkname));
    cri.addOrder(Order.desc("versionCode"));
    List<App> apps = HibernateHelper.list(cri);
    return apps;
}
 
Example 46
Project: Biliomi   File: TamagotchiDao.java   Source Code and License 5 votes vote down vote up
public boolean userHasTamagotchi(User user) {
  return criteria()
      .createAlias("owner", "o")
      .add(Restrictions.and(
          Restrictions.eq("o.id", user.getId()),
          Restrictions.eq("deceased", false)
      ))
      .getCount() > 0;
}
 
Example 47
Project: lemon   File: HibernateGenericDao.java   Source Code and License 5 votes vote down vote up
/**
 * 判断对象某些属性的值在数据库中是否唯一.
 * 
 * @param entityClass
 *            实体类型
 * @param entity
 *            实体对象
 * @param uniquePropertyNames
 *            在POJO里不能重复的属性列表,以逗号分割 如"name,loginid,password"
 * @param <T>
 *            实体类泛型
 * @return 如果唯一返回true,否则返回false
 */
@Transactional(readOnly = true)
public <T> boolean isUnique(Class<T> entityClass, T entity,
        String uniquePropertyNames) throws NoSuchMethodException,
        IllegalAccessException, InvocationTargetException {
    Assert.hasText(uniquePropertyNames);

    Criteria criteria = createCriteria(entityClass).setProjection(
            Projections.rowCount());
    String[] nameList = uniquePropertyNames.split(",");

    // 循环加入唯一列
    for (String name : nameList) {
        String getterMethodName = ReflectUtils.getGetterMethodName(entity,
                name);
        criteria.add(Restrictions.eq(name,
                BeanUtils.invokeMethod(entity, getterMethodName)));
    }

    // 以下代码为了如果是update的情况,排除entity自身.
    String idName = getIdName(entityClass);

    // 取得entity的主键值
    Serializable id = getId(entityClass, entity);

    // 如果id!=null,说明对象已存在,该操作为update,加入排除自身的判断
    if (id != null) {
        criteria.add(Restrictions.not(Restrictions.eq(idName, id)));
    }

    Object result = criteria.uniqueResult();

    return HibernateUtils.getNumber(result) == 0;
}
 
Example 48
Project: gitplex-mit   File: DefaultCodeCommentManager.java   Source Code and License 5 votes vote down vote up
@Sessional
@Override
public Collection<CodeComment> findAll(PullRequest request, ObjectId... commitIds) {
	Preconditions.checkArgument(commitIds.length > 0);
	
	EntityCriteria<CodeComment> criteria = newCriteria();
	criteria.add(Restrictions.eq("request", request));
	List<Criterion> criterions = new ArrayList<>();
	for (ObjectId commitId: commitIds) {
		criterions.add(Restrictions.eq("markPos.commit", commitId.name()));
	}
	criteria.add(Restrictions.or(criterions.toArray(new Criterion[criterions.size()])));
	return findAll(criteria);
}
 
Example 49
Project: ctsms   File: BankIdentificationDaoImpl.java   Source Code and License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
protected Collection<String> handleFindBankNames(String bankCodeNumberPrefix, String bicPrefix, String bankNameInfix, Integer limit)
{
	org.hibernate.Criteria bankIdentificationCriteria = createBankIdentificationCriteria();
	applyBankIdentificationCriterions(bankIdentificationCriteria, bankCodeNumberPrefix, bicPrefix, bankNameInfix);
	bankIdentificationCriteria.add(Restrictions.not(Restrictions.or(Restrictions.eq("bankName", ""), Restrictions.isNull("bankName"))));
	bankIdentificationCriteria.addOrder(Order.asc("bankName"));
	bankIdentificationCriteria.setProjection(Projections.distinct(Projections.property("bankName")));
	CriteriaUtil.applyLimit(limit,
			Settings.getIntNullable(SettingCodes.BANK_NAME_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT, Bundle.SETTINGS, DefaultSettings.BANK_NAME_AUTOCOMPLETE_DEFAULT_RESULT_LIMIT),
			bankIdentificationCriteria);
	return bankIdentificationCriteria.list();
}
 
Example 50
Project: ctsms   File: ECRFFieldDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected long handleGetCountByField(Long inputFieldId) throws Exception {
	org.hibernate.Criteria ecrfFieldCriteria = createEcrfFieldCriteria();
	if (inputFieldId != null) {
		ecrfFieldCriteria.add(Restrictions.eq("field.id", inputFieldId.longValue()));
	}
	return (Long) ecrfFieldCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example 51
Project: ctsms   File: CriterionPropertyDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected Collection<CriterionProperty> handleFindByModule(DBModule module)
		throws Exception {
	org.hibernate.Criteria propertyCriteria = createPropertyCriteria();
	if (module != null) {
		propertyCriteria.add(Restrictions.eq("module", module));
	}
	propertyCriteria.addOrder(Order.asc("id"));
	return propertyCriteria.list();
}
 
Example 52
Project: sdudoc   File: LogDaoImpl.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Pager<SysLog> listLogByUserPage(int userId, int pageNo, int pageSize) {
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(SysLog.class);
	criteria.add(Restrictions.eq("user.id", userId));
	long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	criteria.setProjection(null);
	criteria.addOrder(Order.desc("time"));
	criteria.setFirstResult((pageNo - 1) * pageSize);
	criteria.setMaxResults(pageSize);
	List<SysLog> results = criteria.list();
	return new Pager<SysLog>(pageSize, pageNo, recordTotal, results);
}
 
Example 53
Project: ctsms   File: ECRFFieldValueDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected long handleGetCount(Long ecrfId, String section) throws Exception {
	org.hibernate.Criteria ecrfFieldValueCriteria = createEcrfFieldValueCriteria(null);
	org.hibernate.Criteria ecrfFieldCriteria = ecrfFieldValueCriteria.createCriteria("ecrfField", CriteriaSpecification.INNER_JOIN);
	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")));
	}

	return (Long) ecrfFieldValueCriteria.setProjection(Projections.rowCount()).uniqueResult();
}
 
Example 54
Project: ctsms   File: ECRFStatusEntryDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected Collection<ECRFStatusEntry> handleFindByTrialListEntryValidatedReviewVerified(Long trialId, Long probandListEntryId,
		Boolean validated, Boolean review, Boolean verified, PSFVO psf) throws Exception {
	org.hibernate.Criteria ecrfStatusEntryCriteria = createEcrfStatusEntryCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(ECRFStatusEntry.class, ecrfStatusEntryCriteria);
	if (trialId != null) {
		org.hibernate.Criteria trialCriteria = ecrfStatusEntryCriteria.createCriteria("listEntry");
		trialCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (probandListEntryId != null) {
		ecrfStatusEntryCriteria.add(Restrictions.eq("listEntry.id", probandListEntryId.longValue()));
	}
	if (validated != null || review != null || verified != null) {
		org.hibernate.Criteria statusCriteria = ecrfStatusEntryCriteria.createCriteria("status");
		if (validated != null) {
			statusCriteria.add(Restrictions.eq("validated", validated.booleanValue()));
		}
		if (review != null) {
			statusCriteria.add(Restrictions.eq("review", review.booleanValue()));
		}
		if (verified != null) {
			statusCriteria.add(Restrictions.eq("verified", verified.booleanValue()));
		}
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return ecrfStatusEntryCriteria.list();
}
 
Example 55
Project: ctsms   File: ProbandListStatusEntryDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected ProbandListStatusEntry handleFindLastStatus(
		Long probandListEntryId) throws Exception {
	org.hibernate.Criteria statusEntryCriteria = createStatusEntryCriteria(null);
	if (probandListEntryId != null) {
		statusEntryCriteria.add(Restrictions.eq("listEntry.id", probandListEntryId.longValue()));
	}
	statusEntryCriteria.addOrder(Order.desc("id"));
	statusEntryCriteria.setMaxResults(1);
	return (ProbandListStatusEntry) statusEntryCriteria.uniqueResult();
}
 
Example 56
Project: sjk   File: MarketDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Market getByName(Session session, String marketName) {
    Criteria cri = session.createCriteria(Market.class);
    cri.add(Restrictions.eq("marketName", marketName));
    cri.setCacheable(true);
    return (Market) cri.uniqueResult();
}
 
Example 57
Project: Equella   File: EntityLockingServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
@Transactional
public EntityLock getLock(BaseEntity entity)
{
	EntityLock lock = entityLockDao.findByCriteria(Restrictions.eq("entity", entity));
	if( lock != null )
	{
		if( !CurrentUser.getSessionID().equals(lock.getUserSession()) )
		{
			throw new LockedException(CurrentLocale.get(entity.getName()) + " is locked by another session",
				lock.getUserID(), lock.getUserSession(), entity.getId());
		}
	}
	return lock;
}
 
Example 58
Project: ctsms   File: CriteriaUtil.java   Source Code and License 5 votes vote down vote up
public static void applyStopOpenIntervalCriterion(Criteria intervalCriteria, Timestamp from, Timestamp to, org.hibernate.criterion.Criterion or) {
	if (intervalCriteria != null) {
		if (from != null && to != null) {
			if (to.before(from)) {
				throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.INTERVAL_STOP_BEFORE_START, DefaultMessages.INTERVAL_STOP_BEFORE_START));
			}
			intervalCriteria.add(applyOr(
					Restrictions.or(
							Restrictions.or( // partial interval overlappings:
									Restrictions.and(Restrictions.ge("start", from), Restrictions.lt("start", to)),
									Restrictions.and(Restrictions.gt("stop", from), Restrictions.le("stop", to))
									),
									Restrictions.or( // total inclusions:
											Restrictions.and(Restrictions.le("start", from), Restrictions.ge("stop", to)),
											Restrictions.and(Restrictions.le("start", from), Restrictions.isNull("stop"))
											)
							)
							, or));
		} else if (from != null && to == null) {
			intervalCriteria.add(applyOr(
					Restrictions.or(
							Restrictions.or( // partial interval overlappings:
									Restrictions.ge("start", from),
									Restrictions.gt("stop", from)
									),
									Restrictions.and(Restrictions.le("start", from), Restrictions.isNull("stop"))
							)
							, or));
		} else if (from == null && to != null) {
			intervalCriteria.add(applyOr(Restrictions.lt("start", to), or));
		}
	}
}
 
Example 59
Project: uflo   File: GetTaskReminderCommand.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<TaskReminder> execute(Context context) {
	Criteria criteria=context.getSession().createCriteria(TaskReminder.class);
	if(taskId>0){
		criteria.add(Restrictions.eq("taskId",taskId));
	}
	return criteria.list();
}
 
Example 60
Project: ctsms   File: ProbandListEntryTagDaoImpl.java   Source Code and License 5 votes vote down vote up
@Override
protected long handleGetCountByField(Long inputFieldId) throws Exception {
	org.hibernate.Criteria listEntryTagCriteria = createListEntryTagCriteria();
	if (inputFieldId != null) {
		listEntryTagCriteria.add(Restrictions.eq("field.id", inputFieldId.longValue()));
	}
	return (Long) listEntryTagCriteria.setProjection(Projections.rowCount()).uniqueResult();
}