Java Code Examples for org.hibernate.Session#createCriteria()

The following examples show how to use org.hibernate.Session#createCriteria() . 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 File: SbiMetaTableColumnDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public SbiMetaTableColumn loadTableColumnByName(Session session, String name) throws EMFUserError {
	logger.debug("IN");

	SbiMetaTableColumn toReturn = null;
	Session tmpSession = session;
	try {
		Criterion labelCriterrion = Expression.eq("name", name);
		Criteria criteria = tmpSession.createCriteria(SbiMetaTableColumn.class);
		criteria.add(labelCriterrion);
		toReturn = (SbiMetaTableColumn) criteria.uniqueResult();
		if (toReturn == null)
			return null;
	} catch (HibernateException he) {
		logException(he);
		throw new HibernateException(he);
	} finally {
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 2
Source File: CoreDBServiceFacadeImp.java    From AIDR with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<E> getByCriteriaWithLimit(Criterion criterion, Integer count) {
	List<E> fetchedList = new ArrayList<E>();
	Session session = getCurrentSession();
	Criteria criteria = session.createCriteria(entityClass);
	criteria.add(criterion);
	if(count != null && count > 0){
		criteria.setMaxResults(count);
	}
	try {	
		fetchedList = criteria.list();
		return fetchedList;
	} catch (Exception e) {
		logger.error("getByCriteriaWithLimit failed, criteria = " + criterion.toString(), e);
		throw new HibernateException("getByCriteriaWithLimit failed, criteria = " + criterion.toString());
	}
}
 
Example 3
Source File: SbiMetaTableColumnDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Load all tablecolumn column linked to a table.
 *
 * @param session
 *            the session
 *
 * @return List of meta tables
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaTableColumnDAOHibImpl#loadTableColumnsFromTable(session, tableId)
 */
@Override
public List<SbiMetaTableColumn> loadTableColumnsFromTable(Session session, int tableId) throws EMFUserError {
	logger.debug("IN");

	List<SbiMetaTableColumn> toReturn = null;

	try {
		Criterion labelCriterrion = Expression.eq("sbiMetaTable.tableId", tableId);
		Criteria criteria = session.createCriteria(SbiMetaTableColumn.class);
		criteria.add(labelCriterrion);

		toReturn = criteria.list();

	} catch (HibernateException he) {
		logException(he);
		throw new HibernateException(he);
	} finally {
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 4
Source File: DatabaseMatrixStorage.java    From sailfish-core with Apache License 2.0 6 votes vote down vote up
/**
 * Loads stored matrices from database.
 * Inspects passed map to contains rubbish matrices. Removes them from passed map and tries to remove from database.
 * @param session Hibernate session
 * @return Map matrix paths to {@link StoredMatrix} from database
 */
private Map<String, StoredMatrix> loadStoredMatrices(Session session) {
    Criteria query = session.createCriteria(StoredMatrix.class);

    Map<String, StoredMatrix> storedMatrixMap = ((List<StoredMatrix>)query.list()).stream()
            .collect(Collectors.toMap(StoredMatrix::getFilePath, Function.identity()));

    for(Iterator<StoredMatrix> iterator = storedMatrixMap.values().iterator(); iterator.hasNext(); ) {
        StoredMatrix storedMatrix = iterator.next();

        if (!isValidMatrixPath(storedMatrix.getFilePath())) {
            iterator.remove();

            try {
                session.delete(storedMatrix);
            } catch (HibernateException e) {
                logger.error("Rubbish matrix '{}' can't be deleted from database", storedMatrix.getFilePath(), e);
            }
        }
    }

    return storedMatrixMap;
}
 
Example 5
Source File: SearchImages.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiImages.class);
	if (name != null && !name.isEmpty()) {
		c.add(Restrictions.like("name", name, MatchMode.ANYWHERE).ignoreCase());
	}
	if (description != null && !description.isEmpty()) {
		c.add(Restrictions.like("description", description, MatchMode.ANYWHERE).ignoreCase());
	}
	if (sort != null) {
		for (Entry<OrderBy, Direction> entry : sort.entrySet()) {
			String orderField = "";
			switch (entry.getKey()) {
			case name:
				orderField = "name";
				break;
			case timeIn:
				orderField = "commonInfo.timeIn";
				break;
			}
			c.addOrder(Direction.asc.equals(entry.getValue()) ? Order.asc(orderField) : Order.desc(orderField));
		}
	}
	return c;
}
 
Example 6
Source File: SearchtWlistByGlossaryIdAndWordId.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Criteria evaluate(Session session) {

	if (glossaryId == null || wordId == null) {
		logger.debug("SearchtWlistByGlossaryIdAndWordId, glossaryId or wordId =null");
		return null;
	}

	Criteria c = session.createCriteria(SbiGlWlist.class, "wlist");
	c.createAlias("wlist.content", "contentWl");
	c.createAlias("contentWl.glossary", "glossaryWl");
	c.createAlias("word", "wordWl");
	c.add(Restrictions.eq("glossaryWl.glossaryId", glossaryId));
	c.add(Restrictions.eq("wordWl.wordId", wordId));

	return c;
}
 
Example 7
Source File: DrugsDAOImpl.java    From icure-backend with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mpp getInfos(MppId medecinePackageID) {
	log.debug("Getting infos for Mpp " + medecinePackageID);
	Session sess = getSessionFactory().getCurrentSession();
	Criteria c = sess.createCriteria(Mpp.class);
	c.add(Restrictions.eq("id", medecinePackageID));
	c.setFetchMode("mp", FetchMode.JOIN);
	List<Mpp> result = c.list();
	if (result.size() == 0) {
		return null;
	}
	Validate.isTrue(result.size() == 1, "More than One Mpp found!");
	return result.get(0);
}
 
Example 8
Source File: KickstartFactory.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup a list of all KickstartData objects located on the Satellite
 *  Should not be used by much.  Ignores org!
 * @return List of KickstartData objects if found
 */
public static List<KickstartData> listAllKickstartData() {
    Session session = getSession();
    Criteria c = session.createCriteria(KickstartData.class);
    // Hibernate does not filter out duplicate references by default
    c.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return c.list();
}
 
Example 9
Source File: SCCCachingFactory.java    From uyuni with 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 10
Source File: DrugsDAOImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Doc> getRootDocs(String lang) {
    Session sess = this.getSessionFactory().getCurrentSession();
    Criteria c = sess.createCriteria(Doc.class);
    addLangRestriction(c, lang);
    c.add(Restrictions.sqlRestriction("parent_id is null"));
    c.addOrder(Order.asc("docindex"));
    List<Doc> result = c.list();
    return result;
}
 
Example 11
Source File: ObjFuncOrganizerHIBDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List loadDocumentsByFolder(Integer folderId) {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	List listOfDocuments = null;
	List toReturn = new ArrayList();
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		Criteria criteria = aSession.createCriteria(SbiObjFuncOrganizer.class);
		criteria.add(Restrictions.eq("id.sbiFunctionsOrganizer.functId", folderId));
		listOfDocuments = criteria.list();
		Iterator it = listOfDocuments.iterator();

		while (it.hasNext()) {
			SbiObjFuncOrganizer hibObj = (SbiObjFuncOrganizer) it.next();
			toReturn.add(toDocumentOrganizer(hibObj));
		}

		return toReturn;
	} catch (HibernateException he) {
		logException(he);
		logger.error("HibernateException", he);
		if (tx != null)
			tx.rollback();
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 12
Source File: SCCCachingFactory.java    From uyuni with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Lookup all repositories.
 * @return list of repositories
 */
@SuppressWarnings("unchecked")
public static List<SCCRepository> lookupRepositories() {
    log.debug("Retrieving repositories from cache");
    Session session = getSession();
    Criteria c = session.createCriteria(SCCRepository.class);
    return c.list();
}
 
Example 13
Source File: TestHibernate.java    From MiniWeChat-Server with MIT License 5 votes vote down vote up
public static void query2(){
	Session session = HibernateSessionFactory.getSession();
	Criteria criteria = session.createCriteria(Chatting.class);
	criteria.add(Restrictions.eq("id",new Long(1)));
	List list =criteria.list();
	if(null != list && list.size()>0){
		Chatting chat = (Chatting)list.get(0);
		System.out.println(chat.getSenderUserId()+" "+chat.getReceiverUserId()+" "+chat.getMessage());
	}
}
 
Example 14
Source File: UserDaoImpl.java    From sdudoc with MIT License 5 votes vote down vote up
@Override
public Pager<User> listUserByPage(int pageNo, int pageSize) {
	Session session = sessionFactory.getCurrentSession();
	Criteria criteria = session.createCriteria(User.class);
	long recordTotal = ((Long) criteria.setProjection(Projections.rowCount()).uniqueResult()).longValue();
	criteria.setProjection(null);
	criteria.addOrder(Order.desc("registerDate"));
	criteria.setFirstResult((pageNo - 1) * pageSize);
	criteria.setMaxResults(pageSize);
	List<User> results = criteria.list();
	return new Pager<User>(pageSize, pageNo, recordTotal, results);
}
 
Example 15
Source File: ChannelFamilyFactory.java    From spacewalk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 16
Source File: MenuDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Load menu by id.
 *
 * @param menuID the menu id
 *
 * @return the menu
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.wapp.dao.IMenuDAO#loadMenuByID(integer)
 */
@Override
public Menu loadMenuByID(Integer menuID) throws EMFUserError {
	Menu toReturn = null;
	Session tmpSession = null;
	Transaction tx = null;

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

		Criterion domainCdCriterrion = Expression.eq("menuId", menuID);
		Criteria criteria = tmpSession.createCriteria(SbiMenu.class);
		criteria.add(domainCdCriterrion);
		SbiMenu hibMenu = (SbiMenu) criteria.uniqueResult();
		if (hibMenu == null)
			return null;

		// SbiMenu hibMenu = (SbiMenu)tmpSession.load(SbiMenu.class,
		// menuID);
		toReturn = toMenu(hibMenu, null);
		// toReturn = toMenu(loadSbiMenuByID(menuID), null);

	} 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 toReturn;
}
 
Example 17
Source File: DaoUtil.java    From kardio with 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 18
Source File: SbiMetaTableDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Insert a metatable.
 *
 * @param aMetaSource
 *            the sbimetatable to insert
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaTableDAOHibImpl#insertSource(SbiMetaTable)
 */
@Override
public Integer insertTable(SbiMetaTable aMetaTable) throws EMFUserError {
	logger.debug("IN");

	Session tmpSession = null;
	Transaction tx = null;
	Integer idToReturn = null;

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

		SbiMetaTable hibMeta = new SbiMetaTable();
		hibMeta.setName(aMetaTable.getName());
		hibMeta.setDeleted(aMetaTable.isDeleted());

		SbiMetaSource metaSource = null;
		if (aMetaTable.getSbiMetaSource() != null) {
			Criterion aCriterion = Expression.eq("sourceId", aMetaTable.getSbiMetaSource().getSourceId());
			Criteria criteria = tmpSession.createCriteria(SbiMetaSource.class);
			criteria.add(aCriterion);
			metaSource = (SbiMetaSource) criteria.uniqueResult();
			if (metaSource == null) {
				throw new SpagoBIDAOException("The Domain with value_id= " + aMetaTable.getSbiMetaSource().getSourceId() + " does not exist");
			}
			hibMeta.setSbiMetaSource(metaSource);
		}

		updateSbiCommonInfo4Insert(hibMeta);
		idToReturn = (Integer) tmpSession.save(hibMeta);
		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 idToReturn;
}
 
Example 19
Source File: SearchWsEventNotConsumed.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiWsEvent.class);
	c.add(Restrictions.isNull("takeChargeDate"));
	return c;
}
 
Example 20
Source File: DetailedEventsManagerImpl.java    From sakai with Educational Community License v2.0 4 votes vote down vote up
private Optional<Criteria> basicCriteriaForTrackingParams(Session session, final TrackingParams params)
{
	Criteria crit = session.createCriteria(DetailedEventImpl.class);
	if (StringUtils.isNotBlank(params.siteId))
	{
		crit.add(Restrictions.eq(SITE_ID_COL, params.siteId));
	}
	if (!params.events.isEmpty())
	{
		crit.add(Restrictions.in(EVENT_ID_COL, params.events));
	}

	// Filter out any users who do not have the can be tracked permission in the site
	List<String> filtered = params.userIds.stream()
			.filter(u -> statsAuthz.canUserBeTracked(params.siteId, u))
			.collect(Collectors.toList());
	// must have at least one user
	if (filtered.isEmpty())
	{
		return Optional.empty();
	}
	crit.add(Restrictions.in(USER_ID_COL, filtered));

	if (!TrackingParams.NO_DATE.equals(params.startDate))
	{
		crit.add(Restrictions.ge(EVENT_DATE_COL, Date.from(params.startDate)));
	}
	if (!TrackingParams.NO_DATE.equals(params.endDate))
	{
		crit.add(Restrictions.lt(EVENT_DATE_COL, Date.from(params.endDate)));
	}

	// filter out anonymous events
	Set<String> anonEvents = regServ.getAnonymousEventIds();
	if (!anonEvents.isEmpty())
	{
		crit.add(Restrictions.not(Restrictions.in(EVENT_ID_COL, anonEvents)));
	}

	return Optional.of(crit);
}