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.
Example 1
Project: kardio   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
Project: AIDR   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
Project: kardio   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
Project: Knowage-Server   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
Project: sakai   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
Project: DataHubSystem   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
@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
Project: kardio   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
@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
Project: sakai   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
@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
Project: SensorWebClient   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
@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
Project: AIDR   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
@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
@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
Project: 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
Project: lams   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
Project: lams   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
@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
Project: lams   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
Project: SensorWebClient   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
Project: sakai   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
Project: webcurator   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
Project: lams   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
Project: SensorWebClient   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
Project: SensorWebClient   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
Project: sakai   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
Project: uyuni   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
@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;
}
 
Example 31
Project: uyuni   File: SUSEProductFactory.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find all {@link SUSEProductExtension}.
 * @return list of product extension
 */
@SuppressWarnings("unchecked")
public static List<SUSEProductExtension> findAllSUSEProductExtensions() {
    Session session = getSession();
    Criteria c = session.createCriteria(SUSEProductExtension.class);
    return c.list();
}
 
Example 32
Project: Spring-MVC-Blueprints   File: ReportDaoImpl.java    License: MIT License 5 votes vote down vote up
@Transactional
@Override
public Tblfaculty getFacultyId(String username) {
       Session session = this.sessionFactory.getCurrentSession();
	Criteria crit = session.createCriteria(Tblfaculty.class);
	crit.add(Restrictions.like("username",username));
	
	List<Tblfaculty> faculty = crit.list();
	
	return faculty.get(0);
}
 
Example 33
Project: lams   File: CriteriaQueryTranslator.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getColumn(Criteria criteria, String propertyName) {
	String[] cols = getColumns( propertyName, criteria );
	if ( cols.length != 1 ) {
		throw new QueryException( "property does not map to a single column: " + propertyName );
	}
	return cols[0];
}
 
Example 34
Project: Knowage-Server   File: SbiMetaTableColumnDAOHibImpl.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void modifyTableColumn(Session session, SbiMetaTableColumn aMetaTableColumn) throws EMFUserError {
	logger.debug("IN");

	Session tmpSession = session;

	try {
		SbiMetaTableColumn hibMeta = (SbiMetaTableColumn) tmpSession.load(SbiMetaTableColumn.class, aMetaTableColumn.getColumnId());

		hibMeta.setName(aMetaTableColumn.getName());
		hibMeta.setType(aMetaTableColumn.getType());
		hibMeta.setDeleted(aMetaTableColumn.isDeleted());

		SbiMetaTable metaTable = null;
		if (aMetaTableColumn.getSbiMetaTable().getTableId() < 0) {
			Criterion aCriterion = Expression.eq("valueId", aMetaTableColumn.getSbiMetaTable().getTableId());
			Criteria criteria = tmpSession.createCriteria(SbiMetaSource.class);
			criteria.add(aCriterion);
			metaTable = (SbiMetaTable) criteria.uniqueResult();
			if (metaTable == null) {
				throw new SpagoBIDAOException("The SbiMetaTable with id= " + aMetaTableColumn.getSbiMetaTable().getTableId() + " does not exist");
			}
			hibMeta.setSbiMetaTable(metaTable);
		}

		updateSbiCommonInfo4Update(hibMeta);

	} catch (HibernateException he) {
		logException(he);
		throw new HibernateException(he);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 35
Project: SensorWebClient   File: HibernateUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
@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;
}
 
Example 36
Project: kardio   File: AlertSubscribeDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Function to get all global subscriptions from the database
 */
@Override
public List<AlertSubscriptionEntity> getAllGlobalSubscriptions() {
    Session session = sessionFactory.openSession();

    Criteria aseCriteria = session.createCriteria(AlertSubscriptionEntity.class);
    aseCriteria.add(Restrictions.isNull("component"));

    @SuppressWarnings("unchecked")
    List<AlertSubscriptionEntity> alertSubscriptionList = (List<AlertSubscriptionEntity>) aseCriteria.list();
    session.close();

    return alertSubscriptionList;
}
 
Example 37
Project: olat   File: GenericDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Map<String, Object> restrictionNameValues) {
    Criteria criteria = getCurrentSession().createCriteria(type);
    Iterator<String> keys = restrictionNameValues.keySet().iterator();
    while (keys.hasNext()) {
        String restrictionName = keys.next();
        Object restrictionValue = restrictionNameValues.get(restrictionName);
        criteria = criteria.add(Restrictions.eq(restrictionName, restrictionValue));
    }
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return criteria.list();
}
 
Example 38
Project: jeewx   File: GenericBaseCommonDao.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 返回easyui datagrid DataGridReturn模型对象
 */
public DataGridReturn getDataGridReturn(final CriteriaQuery cq,
		final boolean isOffset) {
	Criteria criteria = cq.getDetachedCriteria().getExecutableCriteria(
			getSession());
	CriteriaImpl impl = (CriteriaImpl) criteria;
	// 先把Projection和OrderBy条件取出来,清空两者来执行Count操作
	Projection projection = impl.getProjection();
	final int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	criteria.setProjection(projection);
	if (projection == null) {
		criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
	}
	if (StringUtils.isNotBlank(cq.getDataGrid().getSort())) {
		cq.addOrder(cq.getDataGrid().getSort(), cq.getDataGrid().getOrder());
	}

	// 判断是否有排序字段
	if (!cq.getOrdermap().isEmpty()) {
		cq.setOrder(cq.getOrdermap());
	}
	int pageSize = cq.getPageSize();// 每页显示数
	int curPageNO = PagerUtil.getcurPageNo(allCounts, cq.getCurPage(),
			pageSize);// 当前页
	int offset = PagerUtil.getOffset(allCounts, curPageNO, pageSize);
	if (isOffset) {// 是否分页
		criteria.setFirstResult(offset);
		criteria.setMaxResults(cq.getPageSize());
	} else {
		pageSize = allCounts;
	}
	// DetachedCriteriaUtil.selectColumn(cq.getDetachedCriteria(),
	// cq.getField().split(","), cq.getClass1(), false);
	List list = criteria.list();
	cq.getDataGrid().setResults(list);
	cq.getDataGrid().setTotal(allCounts);
	return new DataGridReturn(allCounts, list);
}
 
Example 39
Project: gorm-hibernate5   File: AbstractHibernateCriteriaBuilder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Criterion that contrains a collection property to be less than or equal to the given size
 *
 * @param propertyName The property name
 * @param size The size to constrain by
 *
 * @return A Criterion instance
 */
public org.grails.datastore.mapping.query.api.Criteria sizeLe(String propertyName, int size) {
    if (!validateSimpleExpression()) {
        throwRuntimeException(new IllegalArgumentException("Call to [sizeLe] with propertyName [" +
                propertyName + "] and size [" + size + "] not allowed here."));
    }

    propertyName = calculatePropertyName(propertyName);
    addToCriteria(Restrictions.sizeLe(propertyName, size));
    return this;
}
 
Example 40
@SuppressWarnings("unchecked")
@Override
public List<Collection> searchByName(String query, Long userId) throws Exception {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(Collection.class);
	criteria.add(Restrictions.ilike("name", query, MatchMode.ANYWHERE));
	criteria.add(Restrictions.eq("owner.id", userId));
	return criteria.list();
}