Java Code Examples for org.hibernate.Criteria#add()

The following examples show how to use org.hibernate.Criteria#add() . 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
@Override
protected Collection<InventoryBooking> handleFindByProbandTrial(Long probandId, Long trialId, Boolean isRelevantForProbandAppointments, Boolean isRelevantForTrialAppointments,
		boolean sort) throws Exception {
	Criteria bookingCriteria = createBookingCriteria();
	if (probandId != null) {
		bookingCriteria.add(Restrictions.eq("proband.id", probandId.longValue()));
	}
	if (trialId != null) {
		bookingCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (isRelevantForProbandAppointments != null || isRelevantForTrialAppointments != null) {
		Criteria categoryCriteria = bookingCriteria.createCriteria("inventory", CriteriaSpecification.INNER_JOIN).createCriteria("category", CriteriaSpecification.INNER_JOIN);
		if (isRelevantForProbandAppointments != null) {
			categoryCriteria.add(Restrictions.eq("relevantForProbandAppointments", isRelevantForProbandAppointments.booleanValue()));
		}
		if (isRelevantForTrialAppointments != null) {
			categoryCriteria.add(Restrictions.eq("relevantForTrialAppointments", isRelevantForTrialAppointments.booleanValue()));
		}
	}
	if (sort) {
		bookingCriteria.addOrder(Order.asc("start"));
	}
	return bookingCriteria.list();
}
 
Example 2
@SuppressWarnings("unchecked")
@Override
public List<HibernateConfigItem> findPollOnByNode(String node, Date onOrAfter, Date before) {
    Criteria criteria = currentSession().createCriteria(HibernateConfigItem.class)
                                .add(Restrictions.eq("node", node));
    if (onOrAfter == null && before == null) {
        criteria.add(Restrictions.isNotNull("pollOn"));
    } else {
        if (onOrAfter != null) {
            criteria.add(Restrictions.ge("pollOn", onOrAfter));
        }
        if (before != null) {
            criteria.add(Restrictions.lt("pollOn", before));
        }
    }
    return criteria.list();
}
 
Example 3
@SuppressWarnings("unchecked")
@Override
@Transactional
public List<UserAccount> getCollaboratorsByCollection(Long collectionId) {
	Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionCollaborator.class);
	criteria.add(Restrictions.eq("collection.id", collectionId));
	List<CollectionCollaborator> collections = (List<CollectionCollaborator>) criteria.list();
	
	List<UserAccount> collaborators = new ArrayList<UserAccount>();
	if(collections != null) {
		for(CollectionCollaborator collaborator : collections) {
			collaborators.add(collaborator.getAccount());
		}
	}
	return collaborators;
}
 
Example 4
@Override
public SbiTenant loadTenantById(Integer id) throws EMFUserError {
	logger.debug("IN");
	SbiTenant tenant = null;
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		Criterion labelCriterrion = Expression.eq("id", id);
		Criteria criteria = tmpSession.createCriteria(SbiTenant.class);
		criteria.add(labelCriterrion);
		tenant = (SbiTenant) criteria.uniqueResult();

		tx.commit();
	} catch (HibernateException he) {
		logger.error("Error while loading the tenant with id " + id, he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}
	logger.debug("OUT");
	return tenant;
}
 
Example 5
@Override
public List<SbiMetaBcAttribute> loadAllBCAttributeFromBC(int bcId) throws EMFUserError {
	logger.debug("IN");

	List toReturn = null;
	Session tmpSession = null;
	Transaction tx = null;

	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Criterion labelCriterrion = Expression.eq("bcId", bcId);
		Criteria criteria = tmpSession.createCriteria(SbiMetaBcAttribute.class);
		criteria.add(labelCriterrion);

		toReturn = criteria.list();
		if (toReturn == null)
			return null;
		tx.commit();

	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example 6
@Override
protected Collection<ProbandListEntry> handleFindByTrialGroupProbandCountPerson(
		Long trialId, Long probandGroupId, Long probandId, boolean total,
		Boolean person, PSFVO psf) throws Exception {
	org.hibernate.Criteria listEntryCriteria = createListEntryCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(ProbandListEntry.class, listEntryCriteria);
	if (trialId != null) {
		listEntryCriteria.add(Restrictions.eq("trial.id", trialId.longValue()));
	}
	if (probandGroupId != null) {
		listEntryCriteria.add(Restrictions.eq("group.id", probandGroupId.longValue()));
	}
	if (probandId != null || person != null) {
		Criteria probandCriteria = criteriaMap.createCriteria("proband", CriteriaSpecification.INNER_JOIN);
		if (probandId != null) {
			probandCriteria.add(Restrictions.idEq(probandId.longValue()));
		}
		if (person != null) {
			probandCriteria.add(Restrictions.eq("person", person.booleanValue()));
		}
	}
	if (!total) {
		criteriaMap.createCriteria("lastStatus.status", CriteriaSpecification.INNER_JOIN).add(Restrictions.eq("count", true));
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return listEntryCriteria.list();
}
 
Example 7
@Override
public Criteria createCriteria(final Criterion... criterions) {
	Criteria criteria = getSession().createCriteria(entityClass);
	for (Criterion c : criterions) {
		criteria.add(c);
	}
	return criteria;
}
 
Example 8
@SuppressWarnings("unchecked")
public Mp getExtendedInfos(MpId medecineID) {
	log.debug("Getting infos for Mp " + medecineID);
	Session sess = getSessionFactory().getCurrentSession();
	Criteria c = sess.createCriteria(Mp.class);
	c.add(Restrictions.eq("id", medecineID));
	List<Mp> result = c.list();
	if (result.size() == 0) {
		return null;
	}
	Validate.isTrue(result.size() == 1, "More than One Mp found!");

	return result.get(0);
}
 
Example 9
@Override
protected Collection<InventoryStatusEntry> handleFindByOriginator(
		Long staffId, PSFVO psf) throws Exception {
	Criteria statusEntryCriteria = createStatusEntryCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(InventoryStatusEntry.class, statusEntryCriteria);
	if (staffId != null) {
		statusEntryCriteria.add(Restrictions.eq("originator.id", staffId.longValue()));
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return statusEntryCriteria.list();
}
 
Example 10
/**
 * Load map by name.
 *
 * @param name
 *            the name
 *
 * @return the geo map
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.mapcatalogue.dao.geo.bo.dao.ISbiGeoMapsDAO#loadMapByName(string)
 */
@Override
public GeoMap loadMapByName(String name) throws EMFUserError {
	GeoMap biMap = null;
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		Criterion labelCriterrion = Expression.eq("name", name);
		Criteria criteria = tmpSession.createCriteria(SbiGeoMaps.class);
		criteria.add(labelCriterrion);
		// List tmpLst = criteria.list();
		// return first map (unique)
		// if (tmpLst != null && tmpLst.size()>0) biMap = (SbiGeoMaps)tmpLst.get(0);
		// if (tmpLst != null && tmpLst.size()>0) biMap = (SbiGeoMaps)tmpLst.get(0);
		SbiGeoMaps hibMap = (SbiGeoMaps) criteria.uniqueResult();
		if (hibMap == null)
			return null;
		biMap = hibMap.toGeoMap();

		tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}
	return biMap;
}
 
Example 11
/**
 * Load menu by name.
 *
 * @param name the name
 *
 * @return the menu
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.wapp.dao.IMenuDAO#loadMenuByName(string)
 */
@Override
public Menu loadMenuByName(String name) throws EMFUserError {
	Menu biMenu = null;
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();
		Criterion labelCriterrion = Expression.eq("name", name);
		Criteria criteria = tmpSession.createCriteria(SbiMenu.class);
		criteria.add(labelCriterrion);
		SbiMenu hibMenu = (SbiMenu) criteria.uniqueResult();
		if (hibMenu == null)
			return null;
		biMenu = toMenu(hibMenu, null);

		// tx.commit();
	} catch (HibernateException he) {
		logException(he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (tmpSession != null) {
			if (tmpSession.isOpen())
				tmpSession.close();
		}
	}
	return biMenu;
}
 
Example 12
/**
 * Load root low functionality.
 *
 * @param recoverBIObjects
 *            the recover bi objects
 *
 * @return the low functionality
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#loadRootLowFunctionality(boolean)
 */
@Override
public LowFunctionality loadRootLowFunctionality(boolean recoverBIObjects) throws EMFUserError {
	logger.debug("IN");
	LowFunctionality funct = null;
	funct = getFromCache(ROOT);
	if (funct == null) {
		Session aSession = null;
		Transaction tx = null;
		try {
			aSession = getSession();
			tx = aSession.beginTransaction();
			/* ********* start luca changes *************** */
			// Criterion filters = Expression.isNull("parentFunct");
			Criterion filters = Expression.and(Expression.isNull("parentFunct"), Expression.eq("functTypeCd", "LOW_FUNCT"));
			/* ************ end luca changes ************** */
			Criteria criteria = aSession.createCriteria(SbiFunctions.class);
			criteria.add(filters);
			SbiFunctions hibFunct = (SbiFunctions) criteria.uniqueResult();
			if (hibFunct == null)
				return null;
			funct = toLowFunctionality(hibFunct, recoverBIObjects);
			tx.commit();
		} catch (HibernateException he) {
			logger.error("HibernateException", he);
			if (tx != null)
				tx.rollback();
			throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
		} finally {
			if (aSession != null) {
				if (aSession.isOpen())
					aSession.close();
			}
		}
		putIntoCache(ROOT, funct);
	}
	logger.debug("OUT");
	return funct;
}
 
Example 13
/**
 * @inheritDoc
 */
@Override
protected Collection<InventoryBooking> handleFindByInventory(Long inventoryId, PSFVO psf) throws Exception {
	Criteria bookingCriteria = createBookingCriteria();
	SubCriteriaMap criteriaMap = new SubCriteriaMap(InventoryBooking.class, bookingCriteria);
	if (inventoryId != null) {
		bookingCriteria.add(Restrictions.eq("inventory.id", inventoryId.longValue()));
	}
	CriteriaUtil.applyPSFVO(criteriaMap, psf);
	return bookingCriteria.list();
}
 
Example 14
/**
 * @inheritDoc
 */
@Override
protected Collection<ProbandStatusEntry> handleFindByDepartmentCategoryInterval(Long departmentId, Long probandCategoryId, Timestamp from, Timestamp to, Boolean probandActive,
		Boolean available, Boolean hideAvailability) {
	Criteria statusEntryCriteria = createStatusEntryCriteria();
	CriteriaUtil.applyStopOpenIntervalCriterion(statusEntryCriteria, from, to, null);
	if (probandActive != null || hideAvailability != null) {
		Criteria typeCriteria = statusEntryCriteria.createCriteria("type", CriteriaSpecification.INNER_JOIN);
		if (probandActive != null) {
			typeCriteria.add(Restrictions.eq("probandActive", probandActive.booleanValue()));
		}
		if (hideAvailability != null) {
			typeCriteria.add(Restrictions.eq("hideAvailability", hideAvailability.booleanValue()));
		}
	}
	if (departmentId != null || available != null) {
		Criteria probandCriteria = statusEntryCriteria.createCriteria("proband", CriteriaSpecification.INNER_JOIN);
		if (departmentId != null) {
			probandCriteria.add(Restrictions.eq("department.id", departmentId.longValue()));
		}
		if (probandCategoryId != null) {
			probandCriteria.add(Restrictions.eq("category.id", probandCategoryId.longValue()));
		}
		if (available != null) {
			probandCriteria.add(Restrictions.eq("available", available.booleanValue()));
		}
	}
	return statusEntryCriteria.list();
}
 
Example 15
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiGlBnessClsWlist.class);
	c.add(Restrictions.eq("id.bcId", metaBcId));
	c.add(Restrictions.eq("id.wordId", word_id));
	c.add(Restrictions.eq("id.column_name", column));
	return c;
}
 
Example 16
Source Project: jeewx   File: UserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
public int getUsersOfThisRole(String id) {
	Criteria criteria = getSession().createCriteria(TSRoleUser.class);
	criteria.add(Restrictions.eq("TSRole.id", id));
	int allCounts = ((Long) criteria.setProjection(
			Projections.rowCount()).uniqueResult()).intValue();
	return allCounts;
}
 
Example 17
/**
 * This implementation does not support the 'offset' parameter. The maxResultSize parameter is not used (limiting
 * the result needs to be done after security {@link org.geomajas.internal.layer.vector.GetFeaturesEachStep}). If
 * you expect large results to be returned enable scrollableResultSet to retrieve only as many records as needed.
 */
public Iterator<?> getElements(Filter filter, int offset, int maxResultSize) throws LayerException {
	try {
		Session session = getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());
		if (filter != null) {
			if (filter != Filter.INCLUDE) {
				CriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) featureModel, dateFormat);
				Criterion c = (Criterion) filter.accept(visitor, criteria);
				if (c != null) {
					criteria.add(c);
				}
			}
		}

		// Sorting of elements.
		if (getFeatureInfo().getSortAttributeName() != null) {
			if (SortType.ASC.equals(getFeatureInfo().getSortType())) {
				criteria.addOrder(Order.asc(getFeatureInfo().getSortAttributeName()));
			} else {
				criteria.addOrder(Order.desc(getFeatureInfo().getSortAttributeName()));
			}
		}

		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

		if (isScrollableResultSet()) {
			return (Iterator<?>) new ScrollIterator(criteria.scroll());
		} else {
			List<?> list = criteria.list();
			return list.iterator();
		}
	} catch (HibernateException he) {
		throw new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()
				.getDataSourceName(), filter.toString());
	}
}
 
Example 18
/**
 * Lookup a ChannelFamily by its label
 * @param label the label to search for
 * @param org the Org the Family belongs to, use null if looking for
 *        official RedHat ChannelFamilies
 * @return the ChannelFamily found
 */
public static ChannelFamily lookupByLabel(String label, Org org) {
    Session session = getSession();
    Criteria c = session.createCriteria(ChannelFamily.class);
    c.add(Restrictions.eq("label", label));
    c.add(Restrictions.or(Restrictions.eq("org", org),
          Restrictions.isNull("org")));
    return (ChannelFamily) c.uniqueResult();
}
 
Example 19
Source Project: kardio   File: DaoUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static TpsLatency getCurrentTpsAndLatency(String environment, String componentIdsStrg, boolean isParent,
		String platform, SessionFactory sessionFactory, EnvironmentDao environmentDao) {
	Session session = sessionFactory.openSession();
	List<Integer> comIdList = convertCSVToList(componentIdsStrg);
	
	Criteria crtCurrentCont = session.createCriteria(TpsServiceEntity.class, "tpsLat");
	crtCurrentCont.createCriteria("tpsLat.component", "component");
	if(environment != null && environment.length() != 0 && !environment.equalsIgnoreCase("all")){
		int envId = environmentDao.getEnironmentIdFromName(environment);
		crtCurrentCont.add(Restrictions.eq("environment.environmentId", envId));
	}
	/**
	 * Adding platform criteria for current TPS & Latency.
	 */
	if(platform!=null && !platform.equalsIgnoreCase("All"))
		crtCurrentCont.add(Restrictions.eq("component.platform", platform));
	if (comIdList.size() > 0) {
		if (isParent) {
			crtCurrentCont.add(Restrictions.in("component.parentComponent.componentId", comIdList));				
		} else {
			crtCurrentCont.add(Restrictions.in("component.componentId", comIdList));				
		}
	}
	
	ProjectionList projList = Projections.projectionList();
	projList.add(Projections.sum("tpsValue"));
	projList.add(Projections.sum("latencyValue"));
	crtCurrentCont.setProjection(projList);
	List<Object[]> curTpsLatList = crtCurrentCont.list();
	TpsLatency tpsLat = new TpsLatency();
        for (Object[] aRow : curTpsLatList) {
        	if(aRow[0] == null){
        		continue;
        	}
        	double tpsVal = (double) aRow[0];
            double latencyVal = (double) aRow[1];
            tpsLat.setTpsValue(tpsVal);
            tpsLat.setLatencyValue(latencyVal);
        } 	   
	session.close();
	return tpsLat;
}
 
Example 20
@SuppressWarnings("unchecked")
private void getHistoryEntries(final Session session, final BaseSearchFilter filter, final Set<Integer> idSet, final Class< ? > clazz,
    final boolean searchStringInHistory)
{
  if (log.isDebugEnabled() == true) {
    log.debug("Searching in " + clazz);
  }
  // First get all history entries matching the filter and the given class.
  final String className = ClassUtils.getShortClassName(clazz);
  if (searchStringInHistory == true) {
    final StringBuffer buf = new StringBuffer();
    buf.append("(+className:").append(className);
    if (filter.getStartTimeOfModification() != null || filter.getStopTimeOfModification() != null) {
      final DateFormat df = new SimpleDateFormat(DateFormats.LUCENE_TIMESTAMP_MINUTE);
      df.setTimeZone(DateHelper.UTC);
      buf.append(" +timestamp:[");
      if (filter.getStartTimeOfModification() != null) {
        buf.append(df.format(filter.getStartTimeOfModification()));
      } else {
        buf.append("000000000000");
      }
      buf.append(" TO ");
      if (filter.getStopTimeOfModification() != null) {
        buf.append(df.format(filter.getStopTimeOfModification()));
      } else {
        buf.append("999999999999");
      }
      buf.append("]");
    }
    if (filter.getModifiedByUserId() != null) {
      buf.append(" +userName:").append(filter.getModifiedByUserId());
    }
    buf.append(") AND (");
    final String searchString = buf.toString() + modifySearchString(filter.getSearchString()) + ")";
    try {
      final FullTextSession fullTextSession = Search.getFullTextSession(getSession());
      final org.apache.lucene.search.Query query = createFullTextQuery(HISTORY_SEARCH_FIELDS, null, searchString);
      if (query == null) {
        // An error occured:
        return;
      }
      final FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, HistoryEntry.class);
      fullTextQuery.setCacheable(true);
      fullTextQuery.setCacheRegion("historyItemCache");
      fullTextQuery.setProjection("entityId");
      final List<Object[]> result = fullTextQuery.list();
      if (result != null && result.size() > 0) {
        for (final Object[] oa : result) {
          idSet.add((Integer) oa[0]);
        }
      }
    } catch (final Exception ex) {
      final String errorMsg = "Lucene error message: "
          + ex.getMessage()
          + " (for "
          + this.getClass().getSimpleName()
          + ": "
          + searchString
          + ").";
      filter.setErrorMessage(errorMsg);
      log.info(errorMsg);
    }
  } else {
    final Criteria criteria = session.createCriteria(HistoryEntry.class);
    setCacheRegion(criteria);
    criteria.add(Restrictions.eq("className", className));
    if (filter.getStartTimeOfModification() != null && filter.getStopTimeOfModification() != null) {
      criteria.add(Restrictions.between("timestamp", filter.getStartTimeOfModification(), filter.getStopTimeOfModification()));
    } else if (filter.getStartTimeOfModification() != null) {
      criteria.add(Restrictions.ge("timestamp", filter.getStartTimeOfModification()));
    } else if (filter.getStopTimeOfModification() != null) {
      criteria.add(Restrictions.le("timestamp", filter.getStopTimeOfModification()));
    }
    if (filter.getModifiedByUserId() != null) {
      criteria.add(Restrictions.eq("userName", filter.getModifiedByUserId().toString()));
    }
    criteria.setCacheable(true);
    criteria.setCacheRegion("historyItemCache");
    criteria.setProjection(Projections.property("entityId"));
    final List<Integer> idList = criteria.list();
    if (idList != null && idList.size() > 0) {
      for (final Integer id : idList) {
        idSet.add(id);
      }
    }
  }
}