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

The following examples show how to use org.hibernate.Session#createQuery() . 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: ApplicationView.java    From tutorials with MIT License 8 votes vote down vote up
public Long[] projectionRowCount() {
    final Session session = HibernateUtil.getHibernateSession();
    final CriteriaBuilder cb = session.getCriteriaBuilder();
    final CriteriaQuery<Long> cr = cb.createQuery(Long.class);
    final Root<Item> root = cr.from(Item.class);
    cr.select(cb.count(root));
    Query<Long> query = session.createQuery(cr);
    final List<Long> itemProjected = query.getResultList();
    // session.createCriteria(Item.class).setProjection(Projections.rowCount()).list();
    final Long projectedRowCount[] = new Long[itemProjected.size()];
    for (int i = 0; i < itemProjected.size(); i++) {
        projectedRowCount[i] = itemProjected.get(i);
    }
    session.close();
    return projectedRowCount;
}
 
Example 2
Source File: CollectDaoImpl.java    From sdudoc with MIT License 5 votes vote down vote up
@Override
public boolean deleteCollect(int collectId, int userId) {
	String sql = "delete from Collect where id=:id and userId=:userId";
	Session session = sessionFactory.getCurrentSession();
	Query query = session.createQuery(sql);
	query.setInteger("id", collectId);
	query.setInteger("userId", userId);
	int num = query.executeUpdate();
	if(num > 0)
		return true;
	return false;
}
 
Example 3
Source File: SbiMetaJobDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Checks for tables associated.
 *
 * @param sourceId
 *            the metatable id
 *
 * @return true, if checks for tables associated
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaJobDAOHibImpl#hasTablesAssociated(int)
 */
@Override
public boolean hasTablesAssociated(Integer id) throws EMFUserError {
	boolean bool = false;

	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		String hql = " from SbiMetaJobSource s where s.id.jobId = ?";
		Query aQuery = tmpSession.createQuery(hql);
		aQuery.setInteger(0, id);

		List bcAssociated = aQuery.list();
		if (bcAssociated.size() > 0)
			bool = true;
		else
			bool = false;
		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 bool;
}
 
Example 4
Source File: Frequency.java    From core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns List of Frequency objects for the specified database revision.
 * 
 * @param session
 * @param configRev
 * @return
 * @throws HibernateException
 */
@SuppressWarnings("unchecked")
public static List<Frequency> getFrequencies(Session session, int configRev) 
		throws HibernateException {
	String hql = "FROM Frequency " +
			"    WHERE configRev = :configRev";
	Query query = session.createQuery(hql);
	query.setInteger("configRev", configRev);
	return query.list();
}
 
Example 5
Source File: DBQueryUtil.java    From kardio with Apache License 2.0 5 votes vote down vote up
/**
 * Update the tps_service table with latest tps values. 
 * 
 */
public static void updateTpsService(final int envId, int componentId, float tpsVaule, float latencyValue){
	Session session = HibernateConfig.getSessionFactory().getCurrentSession();
	Transaction txn = session.beginTransaction();
	Query query = session.createQuery(HQLConstants.UPDATE_TPS_SERVICE_DETAILS);
	query.setFloat("tpsVaule", tpsVaule);
	query.setFloat("latencyValue", latencyValue);
	query.setTimestamp("lastUpdateDate", new java.sql.Timestamp(System.currentTimeMillis()));
	query.setLong("compId", componentId);
	query.setLong("environmentId", envId);
	query.executeUpdate();
	txn.commit();
}
 
Example 6
Source File: SbiJobTableDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SbiMetaJobTable loadJobTable(Session session, Integer jobId, Integer tableId) throws EMFUserError {
	logger.debug("IN");

	Session aSession = session;
	SbiMetaJobTable toReturn = null;
	Query hqlQuery = null;

	try {

		hqlQuery = aSession.createQuery(" from SbiMetaJobTable as db where db.id.jobId = ? and db.id.tableId = ? ");
		hqlQuery.setInteger(0, jobId);
		hqlQuery.setInteger(1, tableId);

		List hibList = hqlQuery.list();

		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			toReturn = (SbiMetaJobTable) it.next();
			return toReturn;

		}
	} catch (HibernateException he) {
		logException(he);

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		logger.debug("OUT");
	}

	return toReturn;
}
 
Example 7
Source File: HibernateJpaOperations.java    From micronaut-data with Apache License 2.0 5 votes vote down vote up
private <T> Query<T> buildCriteriaQuery(Session session, @NonNull Class<T> rootEntity, CriteriaBuilder criteriaBuilder, @NonNull Pageable pageable) {
    CriteriaQuery<T> query = criteriaBuilder.createQuery(rootEntity);
    Root<T> root = query.from(rootEntity);
    bindCriteriaSort(query, root, criteriaBuilder, pageable);
    Query<T> q = session.createQuery(
            query
    );
    bindPageable(q, pageable);
    return q;
}
 
Example 8
Source File: TestModuleServiceImpl.java    From fastdfs-zyc with GNU General Public License v2.0 5 votes vote down vote up
@Override
@Transactional(propagation = Propagation.REQUIRED)
public Fdfs_file getFileByFileId(String fileId) {
    Session session = getSession();
    Query query = session.createQuery(" from Fdfs_file f where f.file_id='"+fileId+"'");
    List<Fdfs_file> fileList=query.list();
    if(fileList.size()>0){
        return fileList.get(0);
    }else{
        return  null;
    }

}
 
Example 9
Source File: OAuth2TenantInitializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void init(SourceBean config, Session hibernateSession) {
	logger.debug("IN");
	try {
		String hql = "from SbiTenant";
		Query hqlQuery = hibernateSession.createQuery(hql);
		List<SbiTenant> existingTenants = hqlQuery.list();

		List<String> configuredTenants = getTenants();
		for (String aConfiguredTenant : configuredTenants) {
			if (exists(aConfiguredTenant, existingTenants)) {
				LogMF.debug(logger, "Tenant {0} already exists", aConfiguredTenant);
				writeTenantWriteDefaultDatasource(aConfiguredTenant, hibernateSession);
				break;
			} else {
				LogMF.info(logger, "Tenant {0} does not exist. It will be inserted", aConfiguredTenant);
				writeTenant(aConfiguredTenant, hibernateSession);
				writeTenantProductTypes(aConfiguredTenant, hibernateSession);
				writeTenantWriteDefaultDatasource(aConfiguredTenant, hibernateSession);
				LogMF.debug(logger, "Tenant {0} was inserted", aConfiguredTenant);
				break;
			}
		}
	} catch (Throwable t) {
		logger.error(t.getMessage(), t);
		throw new SpagoBIRuntimeException("An unexpected error occured while initializing Tenants", t);
	} finally {
		logger.debug("OUT");
	}
}
 
Example 10
Source File: BaseDAO.java    From bamboobsc with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public List findList(final String hql, final int offset, final int length) throws Exception {
	List list=null;
	Session hbmSession=this.getCurrentSession();
	if (hbmSession==null) {
		return list;
	}
	try {
		Query query=hbmSession.createQuery(hql);
		query.setFirstResult(offset);
		query.setMaxResults(length);
		list=query.list();
	} catch (Exception e) {
		e.printStackTrace();
	}		
	
	/*
	if (hql==null || this.getHibernateTemplate()==null) {
		return list;
	}
	list=this.getHibernateTemplate().executeFind(
			new HibernateCallback() {
				public Object doInHibernate(Session session) {
					Query query=null;
					List resultList=null;
					try {
						query=session.createQuery(hql);
						query.setFirstResult(offset);
						query.setMaxResults(length);
						resultList=query.list();
					}
					catch (Exception e) {
						e.printStackTrace();
					}
					return resultList;
				}
			}
	);
	*/
	
	return list;
}
 
Example 11
Source File: DataSetDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * @param scope Sent from DatasetResource <br>
 *              Can be: "all", "owned", "enterprise" and "shared", depends on Tab from Workspace/Datasets (MyDataset, Shared, Enterprise, All)
 */
@Override
public List<IDataSet> loadDatasetsByTags(UserProfile user, List<Integer> tagIds, String scope) {
	logger.debug("IN");
	List<IDataSet> toReturn = new ArrayList<>();
	Session session = null;
	Set<Domain> categoryList = null;
	String owner = null;
	String domain = null;
	String[] domains = null;
	try {
		Assert.assertNotNull(user, "UserProfile object cannot be null");

		StringBuffer statement = new StringBuffer("select distinct(dst.dataSet) from SbiDatasetTag dst where dst.dataSet.active = ? ");

		if (scope.equalsIgnoreCase("owned") || scope.equalsIgnoreCase("shared")) {
			owner = user.getUserId().toString();
			if (owner != null) {
				if (scope.equalsIgnoreCase("owned"))
					statement.append("and dst.dataSet.owner = :owner ");
				else
					statement.append("and dst.dataSet.owner != :owner ");
			}
		}

		if (scope.equalsIgnoreCase("enterprise") || scope.equalsIgnoreCase("shared") || scope.equalsIgnoreCase("all")) {
			statement.append("and dst.dataSet.scope.valueCd = :domain ");
			if (scope.equalsIgnoreCase("enterprise"))
				domain = scope.toUpperCase();
			else if (scope.equalsIgnoreCase("shared"))
				domain = "USER";
			else {
				domains = new String[2];
				domains[0] = "USER";
				domains[1] = "ENTERPRISE";
				statement.append("and (dst.dataSet.scope.valueCd = :user or dst.dataSet.scope.valueCd = :enterprise) ");
			}

			categoryList = UserUtilities.getDataSetCategoriesByUser(user);
			if (categoryList != null && !categoryList.isEmpty()) {
				statement.append("and dst.dataSet.category.valueCd in (:categories) ");
			}
		}

		if (!tagIds.isEmpty()) {
			statement.append("and dst.dsTagId.tagId in (:tagIds)");
		}

		session = getSession();
		Query query = session.createQuery(statement.toString());

		// Always get active versions
		query.setBoolean(0, true);

		if (owner != null) {
			query.setString("owner", owner);
		}

		if (domain != null)
			query.setString("domain", domain);

		if (domains != null && domains.length > 0) {
			query.setString("user", domains[0]);
			query.setString("enterprise", domains[1]);
		}

		if (categoryList != null && !categoryList.isEmpty()) {
			Iterator<Domain> it = categoryList.iterator();
			List<String> categoryValues = new ArrayList<>();
			while (it.hasNext()) {
				categoryValues.add(it.next().getValueName());
			}

			query.setParameterList("categories", categoryValues);
		}

		if (!tagIds.isEmpty()) {
			query.setParameterList("tagIds", tagIds);
		}

		toReturn = executeQuery(query, session);
	} catch (Exception e) {
		logger.error("An error has occured while filtering Enterprise Datasets by Tags", e);
		throw new SpagoBIDAOException("An unexpected error has occured while filtering Datasets by Tags", e);
	} finally {
		if (session != null && session.isOpen())
			session.close();
	}

	logger.debug("OUT");
	return toReturn;
}
 
Example 12
Source File: EngineDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Load engine by driver name.
 *
 * @param engineLabel
 *            the driver name
 *
 * @return the engine
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.engines.config.dao.IEngineDAO#loadEngineByID(java.lang.Integer)
 */

@Override
public Engine loadEngineByDriver(String driver) throws EMFUserError {
	logger.debug("IN");
	boolean isFound = false;
	Engine engine = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		logger.debug("engine driver is " + driver);
		aSession = getSession();
		tx = aSession.beginTransaction();

		// Criterion labelCriterrion = Expression.eq("driverNm",
		// driver);
		// Criteria criteria = aSession.createCriteria(SbiEngines.class);
		// criteria.add(labelCriterrion);
		// SbiEngines hibEngine = (SbiEngines) criteria.uniqueResult();

		Query hibQueryProd = aSession.createQuery("select opt.sbiProductType from SbiOrganizationProductType opt "
				+ "where opt.sbiOrganizations.name = :tenant ");
		hibQueryProd.setString("tenant", getTenant());

		List hibListProd = hibQueryProd.list();
		Iterator productIt = hibListProd.iterator();

		while (productIt.hasNext() && !isFound) {
			SbiProductType productType = (SbiProductType) productIt.next();

			Query hibQueryEng = aSession.createQuery("select pte.sbiEngines from SbiProductTypeEngine pte "
					+ "where pte.sbiProductType.label = :productType " + "and pte.sbiEngines.driverNm = :driver");

			hibQueryEng.setString("productType", productType.getLabel());
			hibQueryEng.setString("driver", driver);

			SbiEngines hibEngine = (SbiEngines) hibQueryEng.uniqueResult();

			if (hibEngine != null) {
				isFound = true;
				engine = toEngine(hibEngine);
			}
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.error("Error in retrieving engine by label " + driver, he);

		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	if (engine == null) {
		logger.debug("No engine with driver [" + driver + "] was found.");
	}
	logger.debug("OUT");
	return engine;
}
 
Example 13
Source File: SbiGeoMapFeaturesDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Load maps by feature id.
 * 
 * @param featureId the feature id
 * 
 * @return the list
 * 
 * @throws EMFUserError the EMF user error
 * 
 * @see it.eng.spagobi.mapcatalogue.dao.bo.dao.ISbiGeoMapFeaturesDAO#loadMapsByFeatureId(java.lang.Integer)
 */	
public List loadMapsByFeatureId(Integer featureId) throws EMFUserError {
	Session aSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	String hql = null;
	Query hqlQuery = null;
	
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		/*hql = " from SbiGeoMapFeatures as mf " + 
         "where mf.id.featureId = " + featureId.toString();*/
		
		hql = " from SbiGeoMapFeatures as mf " + 
         "where mf.id.featureId = ?" ;
		
		hqlQuery = aSession.createQuery(hql);
		hqlQuery.setInteger(0, featureId.intValue());
		List hibList = hqlQuery.list();
		
		Iterator it = hibList.iterator();
		ISbiGeoMapsDAO mapDAO = DAOFactory.getSbiGeoMapsDAO();
		SbiGeoMapFeatures tmpMapFeature = null;
		GeoMap tmpMap = null;
		while (it.hasNext()) {				
			tmpMapFeature = (SbiGeoMapFeatures) it.next();
			SbiGeoMapFeaturesId tmpMapFeatureId = tmpMapFeature.getId();				
			tmpMap = mapDAO.loadMapByID(new Integer(tmpMapFeatureId.getMapId()));
			if (tmpMap != null)
				realResult.add((GeoMap)tmpMap);
		}
		tx.commit();
	} catch (HibernateException he) {
		logException(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {			
		if (aSession!=null){
			if (aSession.isOpen()) aSession.close();
		}			
	}
	return realResult;
}
 
Example 14
Source File: DistributionListDaoImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void eraseDistributionListObjects(DistributionList dl, int biobId, String triggername) throws EMFUserError {

	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiDistributionListsObjects hibDistributionListsObjects = new SbiDistributionListsObjects();

		// String hql = "from SbiDistributionListsObjects sdlo where sdlo.sbiDistributionList.dlId=" + dl.getId()+" and sdlo.sbiObjects.biobjId="+biobId;
		String hql = "from SbiDistributionListsObjects sdlo where sdlo.sbiDistributionList.dlId=? and sdlo.sbiObjects.biobjId=?";
		Query query = aSession.createQuery(hql);
		query.setInteger(0, dl.getId());
		query.setInteger(1, biobId);
		List l = query.list();
		if (!l.isEmpty()) {
			Iterator it = l.iterator();
			while (it.hasNext()) {
				SbiDistributionListsObjects temp = (SbiDistributionListsObjects) it.next();
				String xmlstr = temp.getXml();
				SourceBean sb = SourceBean.fromXMLString(xmlstr);
				String trigName = (String) sb.getAttribute("triggerName");
				if (trigName != null && trigName.equals(triggername)) {
					hibDistributionListsObjects = temp;
					aSession.delete(hibDistributionListsObjects);
				}
			}
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.error("Error while erasing Distribution List objects related to the Distribution List " + ((dl == null) ? "" : String.valueOf(dl.getId())),
				he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 9106);

	} catch (SourceBeanException e) {
		logger.error("Error while generating Source Bean");
		e.printStackTrace();
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			logger.debug("OUT");
		}
	}
}
 
Example 15
Source File: BIMetaModelParameterDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void modifyBIMetaModelParameter(BIMetaModelParameter aBIMetaModelParameter) {
	Session session = null;
	Transaction transaction = null;
	try {
		session = getSession();
		transaction = session.beginTransaction();
		SbiMetaModelParameter hibBIMetaModelParameter = (SbiMetaModelParameter) session.load(SbiMetaModelParameter.class, aBIMetaModelParameter.getId());
		if (hibBIMetaModelParameter == null) {
			logger.error("The MetaModelParameter with id=" + aBIMetaModelParameter.getId() + " does not exist.");
		}

		SbiMetaModel hibMetaModel = (SbiMetaModel) session.load(SbiMetaModel.class, aBIMetaModelParameter.getBiMetaModelID());
		SbiParameters aSbiParameter = (SbiParameters) session.load(SbiParameters.class, aBIMetaModelParameter.getParID());

		hibBIMetaModelParameter.setSbiMetaModel(hibMetaModel);
		hibBIMetaModelParameter.setSbiParameter(aSbiParameter);
		hibBIMetaModelParameter.setLabel(aBIMetaModelParameter.getLabel());
		if (aBIMetaModelParameter.getRequired() != null)
			hibBIMetaModelParameter.setReqFl(new Short(aBIMetaModelParameter.getRequired().shortValue()));
		if (aBIMetaModelParameter.getModifiable() != null)
			hibBIMetaModelParameter.setModFl(new Short(aBIMetaModelParameter.getModifiable().shortValue()));
		if (aBIMetaModelParameter.getVisible() != null)
			hibBIMetaModelParameter.setViewFl(new Short(aBIMetaModelParameter.getVisible().shortValue()));
		if (aBIMetaModelParameter.getMultivalue() != null)
			hibBIMetaModelParameter.setMultFl(new Short(aBIMetaModelParameter.getMultivalue().shortValue()));
		hibBIMetaModelParameter.setParurlNm(aBIMetaModelParameter.getParameterUrlName());

		Integer colSpan = aBIMetaModelParameter.getColSpan();
		Integer thickPerc = aBIMetaModelParameter.getThickPerc();

		Integer oldPriority = hibBIMetaModelParameter.getPriority();
		Integer newPriority = aBIMetaModelParameter.getPriority();
		if (!oldPriority.equals(newPriority)) {
			Query query = null;
			if (oldPriority.intValue() > newPriority.intValue()) {
				String hqlUpdateShiftRight = "update SbiMetaModelParameter s set s.priority = (s.priority + 1) where s.priority >= " + newPriority
						+ " and s.priority < " + oldPriority + "and s.sbiMetaModel.id = " + hibMetaModel.getId();
				query = session.createQuery(hqlUpdateShiftRight);
			} else {
				String hqlUpdateShiftLeft = "update SbiMetaModelParameter s set s.priority = (s.priority - 1) where s.priority > " + oldPriority
						+ " and s.priority <= " + newPriority + "and s.sbiMetaModel.id = " + hibMetaModel.getId();
				query = session.createQuery(hqlUpdateShiftLeft);
			}
			query.executeUpdate();
		}
		hibBIMetaModelParameter.setPriority(newPriority);
		hibBIMetaModelParameter.setProg(new Integer(1));
		hibBIMetaModelParameter.setColSpan(colSpan);
		hibBIMetaModelParameter.setThickPerc(thickPerc);

		updateSbiCommonInfo4Update(hibBIMetaModelParameter);
		transaction.commit();
	} catch (HibernateException he) {
		logException(he);
		if (transaction != null)
			transaction.rollback();
		throw new HibernateException(he.getLocalizedMessage(), he);
	} finally {
		if (session != null) {
			if (session.isOpen())
				session.close();
		}
	}
}
 
Example 16
Source File: BIObjectDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public List loadAllBIObjectsFromInitialPath(String initialPath) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	List realResult = new ArrayList();
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		/*
		 * Query hibQuery = aSession.createQuery( "select " + "	distinct(objects) " + "from " +
		 * "	SbiObjects as objects, SbiObjFunc as objFuncs, SbiFunctions as functions " + "where " +
		 * "	objects.biobjId = objFuncs.id.sbiObjects.biobjId " + "	and objFuncs.id.sbiFunctions.functId = functions.functId " + "	and " +
		 * "		(functions.path = '" + initialPath + "' " + "		 or functions.path like '" + initialPath + "/%' ) " + "order by " +
		 * "	objects.label");
		 */

		Query hibQuery = aSession
				.createQuery("select " + "	distinct(objects) " + "from " + "	SbiObjects as objects, SbiObjFunc as objFuncs, SbiFunctions as functions "
						+ "where " + "	objects.biobjId = objFuncs.id.sbiObjects.biobjId " + "	and objFuncs.id.sbiFunctions.functId = functions.functId "
						+ "	and " + "		(functions.path = ? " + "		 or functions.path like ?) " + "order by " + "	objects.label");

		hibQuery.setString(0, initialPath);
		hibQuery.setString(1, initialPath + "%");
		List hibList = hibQuery.list();

		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			realResult.add(toBIObject((SbiObjects) it.next(), aSession));
		}
		tx.commit();
	} catch (HibernateException he) {
		logger.error(he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
	}
	logger.debug("OUT");
	return realResult;
}
 
Example 17
Source File: LowFunctionalityDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Erase low functionality.
 *
 * @param aLowFunctionality
 *            the a low functionality
 * @param profile
 *            the profile
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.analiticalmodel.functionalitytree.dao.ILowFunctionalityDAO#eraseLowFunctionality(it.eng.spagobi.analiticalmodel.functionalitytree.bo.LowFunctionality,
 *      it.eng.spago.security.IEngUserProfile)
 */
@Override
public void eraseLowFunctionality(LowFunctionality aLowFunctionality, IEngUserProfile profile) throws EMFUserError {
	logger.debug("IN");
	Session aSession = null;
	Transaction tx = null;
	try {
		if (hasChild(aLowFunctionality.getId())) {
			HashMap params = new HashMap();
			params.put(PAGE, "BIObjectsPage");
			// params.put(SpagoBIConstants.ACTOR,
			// SpagoBIConstants.ADMIN_ACTOR);
			params.put(SpagoBIConstants.OPERATION, SpagoBIConstants.FUNCTIONALITIES_OPERATION);
			throw new EMFUserError(EMFErrorSeverity.ERROR, 1000, new Vector(), params);
		}
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiFunctions hibFunct = (SbiFunctions) aSession.load(SbiFunctions.class, aLowFunctionality.getId());
		Set oldRoles = hibFunct.getSbiFuncRoles();
		Iterator iterOldRoles = oldRoles.iterator();
		while (iterOldRoles.hasNext()) {
			SbiFuncRole role = (SbiFuncRole) iterOldRoles.next();
			aSession.delete(role);
		}

		// update prog column in other functions
		// String hqlUpdateProg =
		// "update SbiFunctions s set s.prog = (s.prog - 1) where s.prog > "
		// + hibFunct.getProg() + " and s.parentFunct.functId = " +
		// hibFunct.getParentFunct().getFunctId();
		if (hibFunct.getParentFunct() != null) {
			String hqlUpdateProg = "update SbiFunctions s set s.prog = (s.prog - 1) where s.prog > ? " + " and s.parentFunct.functId = ?";
			Query query = aSession.createQuery(hqlUpdateProg);
			query.setInteger(0, hibFunct.getProg().intValue());
			query.setInteger(1, hibFunct.getParentFunct().getFunctId().intValue());
			query.executeUpdate();
		}

		aSession.delete(hibFunct);

		tx.commit();
	} catch (HibernateException he) {
		logger.error("HibernateException", he);

		if (tx != null)
			tx.rollback();

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} catch (EMFUserError emfue) {
		if (tx != null)
			tx.rollback();
		throw emfue;
	} catch (Exception e) {
		logException(e);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null)
			if (aSession != null) {
				if (aSession.isOpen()) {
					aSession.close();
					logger.debug("The [eraseLowFunctionality] occurs. LowFunctionality cache will be cleaned.");
					this.clearCache();
				}
				logger.debug("OUT");
			}
	}
}
 
Example 18
Source File: SbiGeoMapsDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Load map by name and level.
 *
 * @param name
 *            the name
 *
 * @param level
 *            the level
 *
 * @return the geo map
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.mapcatalogue.dao.geo.bo.dao.ISbiGeoMapsDAO#loadMapByNameLevel(string)
 */
@Override
public GeoMap loadMapByHierarchyKey(String hierarchy, String member, String level) throws EMFUserError {
	GeoMap biMap = null;
	Session tmpSession = null;
	Transaction tx = null;
	try {
		tmpSession = getSession();
		tx = tmpSession.beginTransaction();

		Query hqlQuery = tmpSession.createQuery(" from SbiGeoMaps m " + "where m.hierarchyName=:hierarchy and m.memberName = :member and m.level = :level");

		hqlQuery.setString("hierarchy", hierarchy);
		hqlQuery.setString("member", member);
		hqlQuery.setInteger("level", Integer.valueOf(level));

		SbiGeoMaps hibMap = (SbiGeoMaps) hqlQuery.uniqueResult();

		if (hibMap == null) {
			logger.error("SVG with hierarchyName [" + hierarchy + "] and memberName[" + member + "] and level [" + level + "] non found in catalogue. ");
			throw new SpagoBIRuntimeException("SVG with hierarchyName [" + hierarchy + "] and memberName[" + member + "] and level [" + level
					+ "] non found in catalogue.");
		}
		biMap = hibMap.toGeoMap();

		tx.commit();
	} catch (org.hibernate.NonUniqueResultException nhe) {
		logException(nhe);
		if (tx != null)
			tx.rollback();
		throw new SpagoBIRuntimeException("There are more than one SVG loaded with Hierarchy [" + hierarchy + "] - Member [" + member + "] - Level ["
				+ level + "]. Please verify the univocity of the hierarchy keys of the SVG documents!", nhe);
	} 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 19
Source File: JPABaseDao.java    From aerogear-unifiedpush-server with Apache License 2.0 4 votes vote down vote up
protected org.hibernate.Query createHibernateQuery(String hql) {
    Session session = (Session) entityManager.getDelegate();
    return session.createQuery(hql);
}
 
Example 20
Source File: TestUtils.java    From uyuni with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Finds a single instance of a persistent object.
 * @param query The query to find the persistent object should
 * be formulated to ensure a single object is returned or
 * an error will occur.
 * @return Object found or null if not
 * @throws Exception if there was a Hibernate related exception
 */
public static Object lookupTestObject(String query) throws Exception {
    Session session = HibernateFactory.getSession();
    Query q = session.createQuery(query);
    return q.uniqueResult();
}