Java Code Examples for org.hibernate.Criteria

The following examples show how to use org.hibernate.Criteria. 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: kardio   Author: tmobile   File: DBQueryUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * get CurrentHealth Check Details from DB.
 * 
 * @param componentId
 * @param environmentId
 * @param regionID
 * @param healthCheckType
 * @return
 * @
 */
private static HealthCheckVO getCurrentHealthCheckDetails(final int componentId, final int environmentId,
		final long regionID,final HealthCheckType healthCheckType) {
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria hcCrit = session.createCriteria(HealthCheckEntity.class,"hc");
	hcCrit.add(Restrictions.eq("hc.component.componentId", componentId));
	hcCrit.add(Restrictions.eq("hc.environment.environmentId", environmentId));
	hcCrit.add(Restrictions.eq("hc.region.regionId", regionID));
	if(healthCheckType != null) {
		hcCrit.add(Restrictions.eq("hc.healthCheckType.healthCheckTypeId", healthCheckType.getHealthCheckTypeId()));
	}
	hcCrit.setMaxResults(1);
	HealthCheckEntity hcEnt = (HealthCheckEntity) hcCrit.uniqueResult();
	txn.commit();
	if(hcEnt == null){
		return null;
	}
	HealthCheckVO hcVO = new HealthCheckVO();
	hcVO.setHealthCheckId(hcEnt.getHealthCheckId());
	if(hcEnt.getCurrentStatus() != null){
		hcVO.setCurrentStatus(hcEnt.getCurrentStatus().getStatusId());
	}
	return hcVO;
}
 
Example #2
Source Project: AIDR   Author: qcri-social   File: RoleRepositoryImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Role findByRoleType(RoleType roleType) {
	Role role = null;
	
	try {
		Criteria criteria = getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createCriteria(Role.class);
		Criterion criterion = Restrictions.eq("roleType", roleType);
		criteria.add(criterion);
	    role = (Role) criteria.uniqueResult();
	} catch(Exception e) {
		logger.error("Error in fetching data by roleType : " +roleType, e);
	}
	
	return role;
}
 
Example #3
Source Project: kardio   Author: tmobile   File: DBQueryUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get the previous days number of apis for a particular component
 * 
 * @return int
 */
private static int getPreiousNumApis(final int compId, final Date date, final int envId) {
	Calendar cal = Calendar.getInstance();
	cal.setTime(date);
	cal.add(Calendar.DATE, -1);
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Criteria ctrStsCrit = session.createCriteria(ApiStatusEntity.class, "as");
	ctrStsCrit.add(Restrictions.eq("as.component.componentId",compId));
	ctrStsCrit.add(Restrictions.eq("as.environment.environmentId",envId));
	ctrStsCrit.add(Restrictions.eq("as.statusDate", new java.sql.Date(cal.getTimeInMillis())  ));
	ctrStsCrit.setMaxResults(1);
	ApiStatusEntity apiSts =(ApiStatusEntity) ctrStsCrit.uniqueResult();
	int totalApi = 0;
	if(apiSts != null){
		totalApi = apiSts.getTotalApi();
	}
	txn.commit();
	return totalApi;
}
 
Example #4
Source Project: Knowage-Server   Author: KnowageLabs   File: WhatifWorkflowDAOHibImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public List<SbiWhatifWorkflow> getWorkflowByModel(int modelId) {
	logger.debug("IN");
	Session aSession = null;
	try {
		aSession = getSession();
		Criteria criteria = aSession.createCriteria(SbiWhatifWorkflow.class);
		Criterion rest1 = Restrictions.eq("modelId", modelId);
		criteria.add(rest1);
		criteria.addOrder(Order.asc("sequcence"));
		return criteria.list();

	} catch (HibernateException he) {
		logger.error("Error loading workflow for model" + modelId, he);
		throw new SpagoBIRuntimeException("Error loading workflow for model" + modelId, he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
		logger.debug("OUT");
	}

}
 
Example #5
Source Project: sakai   Author: sakaiproject   File: MessageBundleServiceImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public List<MessageBundleProperty> getAllProperties(String locale, String basename, String module) {

    Criteria query = sessionFactory.getCurrentSession().createCriteria(MessageBundleProperty.class);
    query.setCacheable(true);

    if (StringUtils.isNotEmpty(locale)) {
        query.add(Restrictions.eq("locale", locale));
    }
    if (StringUtils.isNotEmpty(basename)) {
        query.add(Restrictions.eq("baseName", basename));
    }
    if (StringUtils.isNotEmpty(module)) {
        query.add(Restrictions.eq("moduleName", module));
    }

    return (List<MessageBundleProperty>) query.list();
}
 
Example #6
Source Project: DataHubSystem   Author: SentinelDataHub   File: NetworkUsageDao.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
public long getDownloadedSizeByUserSince (final User user, final Date date)
{
   Long result =
         getHibernateTemplate ().execute (new HibernateCallback<Long> ()
         {
            @Override
            public Long doInHibernate (Session session)
                  throws HibernateException, SQLException
            {
               Criteria criteria = session.createCriteria (
                     NetworkUsage.class);
               criteria.setProjection (Projections.sum ("size"));
               criteria.add (Restrictions.eq ("isDownload", true));
               criteria.add (Restrictions.eq ("user", user));
               criteria.add (Restrictions.gt ("date", date));
               return (Long) criteria.uniqueResult ();
            }
         });
   return (result == null) ? 0 : result;
}
 
Example #7
Source Project: AIDR   Author: qcri-social   File: ConfidenceStatisticsResourceFacadeImp.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<ConfidenceData> getDataAfterTimestampInBin(String crisisCode, String attributeCode, String labelCode, 
																	Long timestamp, Integer bin) {
	Criteria criteria = getCurrentSession().createCriteria(ConfidenceData.class);
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisCode", crisisCode))
			.add(Restrictions.eq("attributeCode", attributeCode))
			.add(Restrictions.eq("labelCode", labelCode))
			.add(Restrictions.ge("timestamp", timestamp))
			.add(Restrictions.eq("bin", bin));
			
	criteria.add(criterion); 		
	try {
		List<ConfidenceData> objList = (List<ConfidenceData>) criteria.list();
		return objList;
	} catch (HibernateException e) {
		logger.error("exception", e);
		e.printStackTrace();
	}
	return null;	
}
 
Example #8
Source Project: kardio   Author: tmobile   File: K8sPodsStatusDaoImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public long getCurrentNumberOfPods(int envId, String componentIdsStrg, boolean isParentComponents) throws ParseException {
	
	List<Integer> comIdList = DaoUtil.convertCSVToList(componentIdsStrg);
	
	Session session = sessionFactory.openSession();
	DetachedCriteria subMaxDate = DetachedCriteria.forClass(K8sPodsContainersEntity.class);
	subMaxDate.setProjection(Projections.max("statusDate"));
	Criteria crtCurrentCont = session.createCriteria(K8sPodsContainersEntity.class, "contSts");
	crtCurrentCont.createCriteria("contSts.component", "component");
	crtCurrentCont.add(Property.forName("statusDate").eq(subMaxDate));
	
	DaoUtil.addEnvironmentToCriteria(envId, isParentComponents, comIdList, crtCurrentCont);

	crtCurrentCont.setProjection(Projections.sum("totalPods"));
	long currentNumOfCont = (long) (crtCurrentCont.uniqueResult() == null ? (long)0 : crtCurrentCont.uniqueResult());
	session.close();
	return currentNumOfCont;
	
}
 
Example #9
Source Project: AIDR   Author: qcri-social   File: ConfidenceStatisticsResourceFacadeImp.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<ConfidenceData> getDataInIntervalWithBin(String crisisCode, String attributeCode, String labelCode, Long timestamp1,
																	Long timestamp2, Integer bin) {
	Criteria criteria = getCurrentSession().createCriteria(ConfidenceData.class);
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisCode", crisisCode))
			.add(Restrictions.eq("attributeCode", attributeCode))
			.add(Restrictions.eq("labelCode", labelCode))
			.add(Restrictions.ge("timestamp", timestamp1))
			.add(Restrictions.le("timestamp", timestamp2))
			.add(Restrictions.ge("bin", bin));
			
	criteria.add(criterion); 		
	try {
		List<ConfidenceData> objList = (List<ConfidenceData>) criteria.list();
		return objList;
	} catch (HibernateException e) {
		logger.error("exception", e);
		e.printStackTrace();
	}
	return null;
}
 
Example #10
Source Project: sakai   Author: sakaiproject   File: ChatManagerImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
public int getChannelMessagesCount(ChatChannel channel, String context, Date date) {
    if (channel == null) {
        // default to the first one
        List<ChatChannel> channels = getContextChannels(context, true);
        if (channels != null && channels.size() > 0) {
            channel = channels.iterator().next();
        }
    }
    int count = 0;
    if (channel != null) {
        Criteria c = this.getSessionFactory().getCurrentSession().createCriteria(ChatMessage.class);
        c.add(Expression.eq("chatChannel", channel));      
        if (date != null) {
            c.add(Expression.ge("messageDate", date));
        }
        c.setProjection(Projections.rowCount());
        count = ((Long) c.uniqueResult()).intValue();
    }
    return count;
}
 
Example #11
Source Project: AIDR   Author: qcri-social   File: ConfidenceStatisticsResourceFacadeImp.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<ConfidenceData> getDataBeforeTimestampGranularityWithBin(String crisisCode, String attributeCode, String labelCode,
																	Long timestamp, Long granularity, Integer bin) {
	Criteria criteria = getCurrentSession().createCriteria(ConfidenceData.class);
	Criterion criterion = Restrictions.conjunction()
			.add(Restrictions.eq("crisisCode", crisisCode))
			.add(Restrictions.eq("attributeCode", attributeCode))
			.add(Restrictions.eq("labelCode", labelCode))
			.add(Restrictions.le("timestamp", timestamp))
			.add(Restrictions.eq("granularity", granularity))
			.add(Restrictions.ge("bin", bin));
			
	criteria.add(criterion); 		
	try {
		List<ConfidenceData> objList = (List<ConfidenceData>) criteria.list();
		return objList;
	} catch (HibernateException e) {
		logger.error("exception", e);
		e.printStackTrace();
	}
	return null;
}
 
Example #12
Source Project: SensorWebClient   Author: 52North   File: DatabaseAccess.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
	private static List<TimeseriesFeed> findTimeseriesFeedsWith(TimeseriesMetadata timeseriesMetadata, Session session) {
		Criteria criteria = session.createCriteria(TimeseriesFeed.class);
		List<TimeseriesFeed> timeseriesFeeds = criteria
                .add(Restrictions.eq("timeseriesId", timeseriesMetadata.getTimeseriesId()))
//                .add(Restrictions.eq("serviceUrl", timeseriesMetadata.getServiceUrl()))
//                .add(Restrictions.eq("phenomenon", timeseriesMetadata.getPhenomenon()))
//				.add(Restrictions.eq("procedure", timeseriesMetadata.getProcedure()))
//				.add(Restrictions.eq("offering", timeseriesMetadata.getOffering()))
//				.add(Restrictions.eq("featureOfInterest", timeseriesMetadata.getFeatureOfInterest()))
				.list();
		return timeseriesFeeds;
	}
 
Example #13
Source Project: ctsms   Author: phoenixctms   File: ProbandListEntryDaoImpl.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
protected Collection<ProbandListEntry> handleFindByTrialProbandDepartment(
		Long trialId, Long probandDepartmentId) throws Exception {
	org.hibernate.Criteria listEntryCriteria = createListEntryCriteria();
	if (trialId != null) {
		listEntryCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (probandDepartmentId != null) {
		listEntryCriteria.createCriteria("proband", CriteriaSpecification.INNER_JOIN).add(Restrictions.eq("department.id", probandDepartmentId.longValue()));
	}
	return listEntryCriteria.list();
}
 
Example #14
Source Project: AIDR   Author: qcri-social   File: AbstractDaoImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<E> findUniqueByCriteria(Criterion criterion, String uniqueField) {
    Criteria criteria = getCurrentSession().createCriteria(entityClass);
    criteria.add(criterion);
    criteria.setProjection(Projections.distinct(Projections.property(uniqueField)));
    return criteria.list();
}
 
Example #15
Source Project: AIDR   Author: qcri-social   File: ConfidenceStatisticsResourceFacadeImp.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<ConfidenceData> getDataByCrisis(String crisisCode) {
	Criteria criteria = getCurrentSession().createCriteria(ConfidenceData.class);
	criteria.add(Restrictions.eq("crisisCode", crisisCode)); 		
	try {
		List<ConfidenceData> objList = (List<ConfidenceData>) criteria.list();
		return objList;
	} catch (HibernateException e) {
		logger.error("exception", e);
		e.printStackTrace();
	}
	return null;
}
 
Example #16
Source Project: AIDR   Author: qcri-social   File: UserConnectionRepositoryImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<UserConnection> getByUserIdAndProviderUserId(String userId,
		String providerUserId) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(UserConnection.class);
       criteria.add(Restrictions.eq("userId", userId));
       criteria.add(Restrictions.eq("providerUserId", providerUserId));
       return criteria.list();
}
 
Example #17
Source Project: gocd   Author: gocd   File: ServerBackupRepository.java    License: Apache License 2.0 5 votes vote down vote up
public Optional<ServerBackup> lastSuccessfulBackup() {
    List results = (List) getHibernateTemplate().execute((HibernateCallback) session -> {
        Criteria criteria = session.createCriteria(ServerBackup.class);
        criteria.add(Restrictions.eq("status", BackupStatus.COMPLETED));
        criteria.setMaxResults(1);
        criteria.addOrder(Order.desc("id"));
        return criteria.list();
    });

    return results.isEmpty() ? Optional.empty() : Optional.of((ServerBackup) results.get(0));
}
 
Example #18
Source Project: lams   Author: lamsfoundation   File: CriteriaImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public Criteria setProjection(Projection projection) {
	CriteriaImpl.this.projection = projection;
	CriteriaImpl.this.projectionCriteria = this;
	setResultTransformer(PROJECTION);
	return this;
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: CriteriaQueryTranslator.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void createCriteriaSQLAliasMap() {
	int i = 0;
	for(final Criteria crit : criteriaInfoMap.keySet()){
		final CriteriaInfoProvider value = criteriaInfoMap.get( crit );
		String alias = crit.getAlias();
		if ( alias == null ) {
			// the entity name
			alias = value.getName();
		}
		criteriaSQLAliasMap.put( crit, StringHelper.generateAlias( alias, i++ ) );
	}

	criteriaSQLAliasMap.put( rootCriteria, rootSQLAlias );
}
 
Example #20
Source Project: AIDR   Author: qcri-social   File: CollectionRepositoryImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Collection findByCode(String code) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.add(Restrictions.eq("code", code));
	try {
		return (Collection) criteria.uniqueResult();
	} catch (HibernateException e) {
		logger.error("Hibernate exception while finding a collection by code: "+code + "/t"+e.getStackTrace());
		return null;
	}
}
 
Example #21
Source Project: lams   Author: lamsfoundation   File: SimpleExpression.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, CriteriaQuery criteriaQuery) throws HibernateException {
	final String[] columns = criteriaQuery.findColumns( propertyName, criteria );
	final Type type = criteriaQuery.getTypeUsingProjection( criteria, propertyName );
	final StringBuilder fragment = new StringBuilder();

	if ( columns.length > 1 ) {
		fragment.append( '(' );
	}
	final SessionFactoryImplementor factory = criteriaQuery.getFactory();
	final int[] sqlTypes = type.sqlTypes( factory );
	for ( int i = 0; i < columns.length; i++ ) {
		final boolean lower = ignoreCase && (sqlTypes[i] == Types.VARCHAR || sqlTypes[i] == Types.CHAR || 
				sqlTypes[i] == Types.NVARCHAR || sqlTypes[i] == Types.NCHAR);
		if ( lower ) {
			fragment.append( factory.getDialect().getLowercaseFunction() ).append( '(' );
		}
		fragment.append( columns[i] );
		if ( lower ) {
			fragment.append( ')' );
		}

		fragment.append( getOp() ).append( "?" );
		if ( i < columns.length - 1 ) {
			fragment.append( " and " );
		}
	}
	if ( columns.length > 1 ) {
		fragment.append( ')' );
	}
	return fragment.toString();
}
 
Example #22
Source Project: SensorWebClient   Author: 52North   File: HibernateUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Deprecated
@SuppressWarnings("unchecked")
public static List<ComplexRule> searchOwnComplex(String userID, String row, String text) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(ComplexRule.class);
    List<ComplexRule> rules = crit.add(Restrictions.and(Restrictions.eq(OWNER_ID, Integer.valueOf(userID)),
                                                        Restrictions.ilike(row, text))).list();
    session.getTransaction().commit();
    return rules;
}
 
Example #23
Source Project: sakai   Author: sakaiproject   File: ContentReviewItemDao.java    License: Educational Community License v2.0 5 votes vote down vote up
public Optional<ContentReviewItem> findByProviderAndExternalId(Integer providerId, String externalId) {

		Criteria c = sessionFactory.getCurrentSession()
				.createCriteria(ContentReviewItem.class)
				.add(Restrictions.eq("providerId", providerId))
				.add(Restrictions.eq("externalId", externalId));
		
		return Optional.ofNullable((ContentReviewItem) c.uniqueResult());
	}
 
Example #24
Source Project: webcurator   Author: DIA-NZ   File: HierPermMappingDAOImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void deleteMappings(final Site aSite) {
	// Run the deletion.
	txTemplate.execute(
			new TransactionCallback() {
				@SuppressWarnings("unchecked")
				public Object doInTransaction(TransactionStatus ts) {
					try { 
						Criteria query = getSession().createCriteria(Mapping.class);
						query.createCriteria("permission")
						     .createCriteria("site")
						     .add(Restrictions.eq("oid", aSite.getOid()));
						
						List<Mapping> mappings = query.list();
						for(Mapping m: mappings) {
							getSession().delete(m);
						}
					}
					catch(Exception ex) {
						log.debug("Setting Rollback Only", ex);
						ts.setRollbackOnly();
					}
					return null;
				}
			}
	);
	
	// Clear the session to evict anything
	// that we don't want hanging around.	
	getSession().clear();
	
}
 
Example #25
Source Project: lams   Author: lamsfoundation   File: ProjectionList.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String toSqlString(Criteria criteria, int loc, CriteriaQuery criteriaQuery) throws HibernateException {
	final StringBuilder buf = new StringBuilder();
	String separator = "";

	for ( Projection projection : elements ) {
		buf.append( separator ).append( projection.toSqlString( criteria, loc, criteriaQuery ) );
		loc += getColumnAliases( loc, criteria, criteriaQuery, projection ).length;
		separator = ", ";
	}
	return buf.toString();
}
 
Example #26
Source Project: SensorWebClient   Author: 52North   File: HibernateUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static List<Subscription> getUserSubscriptions(String userID) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(Subscription.class);
    List<Subscription> subscriptions = crit.add(Restrictions.eq(USER_ID, Integer.valueOf(userID))).list();
    session.getTransaction().commit();

    return subscriptions;
}
 
Example #27
Source Project: SensorWebClient   Author: 52North   File: HibernateUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Deprecated
@SuppressWarnings("unchecked")
public static void updateComplexRuleSubscribtion(String ruleName, boolean subscribed) {
    Session session = getSessionFactory().getCurrentSession();
    session.beginTransaction();
    Criteria crit = session.createCriteria(ComplexRule.class);
    List<ComplexRule> rules = crit.add(Restrictions.eq(RULE_NAME, ruleName)).list();
    if (rules.size() == 1) {
        ComplexRule rule = rules.get(0);
        rule.setSubscribed(subscribed);
        session.saveOrUpdate(rule);
    }
    session.getTransaction().commit();
}
 
Example #28
Source Project: sakai   Author: sakaiproject   File: StatsUpdateManagerImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
public JobRun getLatestJobRun() throws Exception {
	JobRun r = getHibernateTemplate().execute(session -> {
           JobRun jobRun = null;
           Criteria c = session.createCriteria(JobRunImpl.class);
           c.setMaxResults(1);
           c.addOrder(Order.desc("id"));
           List jobs = c.list();
           if(jobs != null && jobs.size() > 0){
               jobRun = (JobRun) jobs.get(0);
           }
           return jobRun;
       });
	return r;
}
 
Example #29
Source Project: uyuni   Author: uyuni-project   File: SCCCachingFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup a {@link SCCSubscriptionJson} object for given sccId.
 * @param id the scc id
 * @return SCC Subscription or null
 */
public static SCCSubscription lookupSubscriptionBySccId(Long id) {
    if (id == null) {
        return null;
    }
    Session session = getSession();
    Criteria c = session.createCriteria(SCCSubscription.class);
    c.add(Restrictions.eq("sccId", id));
    return (SCCSubscription) c.uniqueResult();
}
 
Example #30
Source Project: AIDR   Author: qcri-social   File: CollectionRepositoryImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Boolean exist(String code) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.add(Restrictions.eq("code", code));
	criteria.add(Restrictions.ne("status", CollectionStatus.TRASHED));
	Collection collection = (Collection) criteria.uniqueResult();
	return collection != null;
}