org.hibernate.Session#createCriteria ( )源码实例Demo

下面列出了org.hibernate.Session#createCriteria ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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;
}
 
@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;
}
 
/**
 * 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;
}
 
源代码4 项目: Knowage-Server   文件: SearchImages.java
@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;
}
 
源代码5 项目: sailfish-core   文件: DatabaseMatrixStorage.java
/**
 * 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;
}
 
源代码6 项目: AIDR   文件: CoreDBServiceFacadeImp.java
@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());
	}
}
 
源代码7 项目: Knowage-Server   文件: MenuDAOImpl.java
/**
 * 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;
}
 
源代码8 项目: spacewalk   文件: ChannelFamilyFactory.java
/**
 * 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();
}
 
源代码9 项目: sdudoc   文件: UserDaoImpl.java
@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);
}
 
源代码10 项目: MiniWeChat-Server   文件: TestHibernate.java
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());
	}
}
 
源代码11 项目: uyuni   文件: SCCCachingFactory.java
/**
 * 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();
}
 
@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;
}
 
源代码13 项目: icure-backend   文件: DrugsDAOImpl.java
@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);
}
 
源代码14 项目: freehealth-connector   文件: DrugsDAOImpl.java
@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;
}
 
源代码15 项目: uyuni   文件: SCCCachingFactory.java
/**
 * 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();
}
 
源代码16 项目: spacewalk   文件: KickstartFactory.java
/**
 * 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();
}
 
源代码17 项目: kardio   文件: DaoUtil.java
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;
}
 
源代码18 项目: Knowage-Server   文件: SbiMetaTableDAOHibImpl.java
/**
 * 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;
}
 
源代码19 项目: Knowage-Server   文件: SearchWsEventNotConsumed.java
@Override
public Criteria evaluate(Session session) {
	Criteria c = session.createCriteria(SbiWsEvent.class);
	c.add(Restrictions.isNull("takeChargeDate"));
	return c;
}
 
源代码20 项目: sakai   文件: DetailedEventsManagerImpl.java
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);
}