Java Code Examples for org.hibernate.Transaction#rollback()

The following examples show how to use org.hibernate.Transaction#rollback() . 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
public SbiAttribute loadSbiAttributeById(Integer id) throws EMFUserError {
	logger.debug("IN");
	SbiAttribute toReturn = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		toReturn = (SbiAttribute) aSession.load(SbiAttribute.class, id);
		Hibernate.initialize(toReturn);
		tx.commit();
	} catch (HibernateException he) {
		logger.error(he.getMessage(), 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 toReturn;
}
 
Example 2
@Override
public void merge(List<E> entityCollection) {
	Session session = getCurrentSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		for (E e: entityCollection) {
			session.merge(e);
			session.flush();
			session.evict(e);
		}
		if (!tx.wasCommitted()) tx.commit();
	} catch (Exception ex) {
		logger.error("Merge list failed", ex);
		tx.rollback();
		throw new HibernateException("Merge list failed");
	}

}
 
Example 3
@Override
public void deleteDatasetTag(SbiDatasetTag dsTag) {
	logger.debug("IN");
	Session session = null;
	Transaction tx = null;
	try {
		session = getSession();
		tx = session.beginTransaction();
		session.delete(dsTag);
		session.flush();
		tx.commit();
	} catch (Exception e) {
		logException(e);
		if (tx != null)
			tx.rollback();
		throw new RuntimeException(e);
	} finally {
		if (session != null && session.isOpen())
			session.close();
	}
	logger.debug("OUT");
}
 
Example 4
/**
 * Load domain by code and value.
 *
 * @param codeDomain
 *            the code domain
 * @param codeValue
 *            the code value
 *
 * @return the domain
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.commons.dao.IDomainDAO#loadDomainByCodeAndValue(java.lang.String, java.lang.String)
 */
@Override
public SbiDomains loadSbiDomainByCodeAndValue(String codeDomain, String codeValue) throws EMFUserError {
	/*
	 * <STATEMENT name="SELECT_DOMAIN_FROM_CODE_VALUE" query="SELECT D.VALUE_NM AS VALUE_NAME, D.VALUE_ID AS VALUE_ID, D.VALUE_CD AS VALUE_CD FROM
	 * SBI_DOMAINS D WHERE DOMAIN_CD = ? AND VALUE_CD = ? "/>
	 */
	SbiDomains aSbiDomains = null;
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();

		Criterion aCriterion = Expression.and(Expression.eq("domainCd", codeDomain), Expression.eq("valueCd", codeValue));
		Criteria criteria = aSession.createCriteria(SbiDomains.class);
		criteria.add(aCriterion);

		aSbiDomains = (SbiDomains) criteria.uniqueResult();
		if (aSbiDomains == null)
			return null;

		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 aSbiDomains;
}
 
Example 5
/**
 * Demonstrates transitive persistence with detached object support
 */
public void bidOnAuction(User bidder, AuctionItem item, float amount) throws Exception {
	System.out.println("Creating a new bid for auction item: " + item.getId() + " by user: " + bidder.getId() );

	Session s = factory.openSession();
	Transaction tx=null;
	try {
		tx = s.beginTransaction();

		s.lock(item, LockMode.NONE);
		s.lock(bidder, LockMode.NONE);

		Bid bid = new Bid();
		bid.setBidder(bidder);
		bid.setDatetime( new Date() );
		bid.setAmount(amount);
		bid.setItem(item);
		bidder.getBids().add(bid);
		item.getBids().add(bid);

		tx.commit();
	}
	catch (Exception e) {
		if (tx!=null) tx.rollback();
		throw e;
	}
	finally {
		s.close();
	}
}
 
Example 6
@Override
public void modifyDsBc(SbiMetaDsBc aMeta) throws EMFUserError {
	logger.debug("IN");

	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiMetaDsBcId hibId = new SbiMetaDsBcId();
		hibId.setBcId(aMeta.getId().getBcId());
		hibId.setDsId(aMeta.getId().getDsId());
		hibId.setOrganization(aMeta.getId().getOrganization());
		hibId.setVersionNum(aMeta.getId().getVersionNum());

		updateSbiCommonInfo4Update(hibId);
		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();
		}

	}
	logger.debug("OUT");
}
 
Example 7
@Override
public byte[] getBinContent(Integer binId) throws HibernateException {
	logger.debug("IN");
	if (binId != null)
		logger.debug("binId=" + binId.toString());
	byte[] content = new byte[0];
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		SbiBinContents hibBinCont = (SbiBinContents) aSession.load(SbiBinContents.class, binId);
		content = hibBinCont.getContent();
		tx.commit();
	} catch (HibernateException he) {
		logger.error("HibernateException", he);
		if (tx != null)
			tx.rollback();
		throw new HibernateException(he.getLocalizedMessage(), he);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}
		logger.debug("OUT");
	}
	return content;
}
 
Example 8
public void testDom4jRetreival() {
	TestData testData = new TestData();
	testData.create();

	Session session = openSession();
	Transaction txn = session.beginTransaction();
	org.hibernate.Session dom4j = session.getSession( EntityMode.DOM4J );

	Object rtn = dom4j.get( Stock.class.getName(), testData.stockId );
	Element element = ( Element ) rtn;

	assertEquals( "Something wrong!", testData.stockId, Long.valueOf( element.attributeValue( "id" ) ) );

	System.out.println( "**** XML: ****************************************************" );
	prettyPrint( element );
	System.out.println( "**************************************************************" );

	Element currVal = element.element( "currentValuation" );

	System.out.println( "**** XML: ****************************************************" );
	prettyPrint( currVal );
	System.out.println( "**************************************************************" );

	txn.rollback();
	session.close();

	testData.destroy();
}
 
Example 9
/**
 * Checks for bi lovs associated.
 *
 * @param dsId the ds id
 * @return true, if checks for lovs associated
 * @throws EMFUserError the EMF user error
 * @see it.eng.spagobi.tools.dataSet.dao.IDataSetDAO#hasBIObjAssociated(java.lang.String)
 */
@Override
public boolean hasBILovAssociated(String dsId) {
	logger.debug("IN");
	boolean bool = false;

	Session session = null;
	Transaction transaction = null;
	try {
		session = getSession();
		transaction = session.beginTransaction();
		Integer dsIdInt = Integer.valueOf(dsId);

		String hql = " from SbiLov s where datasetId = ?";
		Query aQuery = session.createQuery(hql);
		aQuery.setInteger(0, dsIdInt.intValue());
		List biLovAssocitedWithDs = aQuery.list();
		if (biLovAssocitedWithDs.size() > 0)
			bool = true;
		else
			bool = false;
		transaction.commit();
	} catch (Throwable t) {
		if (transaction != null && transaction.isActive()) {
			transaction.rollback();
		}
		throw new SpagoBIDAOException("Error while getting the lovs associated with the data set with id " + dsId, t);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return bool;
}
 
Example 10
/**
 * Gets the document labels list with associated dependencies.
 *
 * @param useId the use id
 *
 * @return the document labels list with associated dependencies
 *
 * @throws EMFUserError the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IObjParuseDAO#getDocumentLabelsListWithAssociatedDependencies(java.lang.Integer)
 */
@Override
public List getDocumentLabelsListWithAssociatedDependencies(Integer useId) throws EMFUserError {
	List toReturn = new ArrayList();
	Session aSession = null;
	Transaction tx = null;
	try {
		aSession = getSession();
		tx = aSession.beginTransaction();
		/*
		 * String hql = "select " + "	distinct(obj.label) " + "from " + "	SbiObjects obj, SbiObjParuse s " + "where " +
		 * "	obj.sbiObjPars.objParId = s.id.sbiObjPar.objParId and " + "	s.id.sbiParuse.useId = " + useId;
		 */
		String hql = "select " + "	distinct(obj.label) " + "from " + "	SbiObjects obj, SbiObjPar p, SbiObjParuse s " + "where "
				+ "	obj.biobjId = p.sbiObject.biobjId and " + "	p.objParId = s.sbiObjPar.objParId and " + "	s.sbiParuse.useId = ?";
		Query query = aSession.createQuery(hql);
		query.setInteger(0, useId.intValue());
		List result = query.list();
		toReturn = result;
		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 toReturn;
}
 
Example 11
/**
 * Roll the transaction for the current session back. This method or
 * {@link #commitTransaction}can only be called once per session.
 *
 * @throws HibernateException if the commit fails
 */
public void rollbackTransaction() throws HibernateException {
    SessionInfo info = threadSessionInfo();
    if (info == null) {
        return;
    }
    if (info.getSession() == null) {
        return;
    }
    Transaction txn = info.getTransaction();
    if (txn != null) {
        txn.rollback();
        info.setTransaction(null);
    }
}
 
Example 12
@Override
public void handleRemoveAllTxn(Set<IcdSyst> icdSysts) throws Exception {
	Transaction transaction = this.getSession(true).beginTransaction();
	try {
		Iterator<IcdSyst> it = icdSysts.iterator();
		while (it.hasNext()) {
			removeIcdSyst(it.next().getId());
		}
		transaction.commit();
	} catch (Exception e) {
		transaction.rollback();
		throw e;
	}
}
 
Example 13
/**
 * Counts number of BIObj associated.
 *
 * @param dsId
 *            the ds id
 * @return Integer, number of BIObj associated
 * @throws EMFUserError
 *             the EMF user error
 */
@Override
public Integer countFederationsUsingDataset(Integer dsId) {
	logger.debug("IN");
	Integer resultNumber = new Integer(0);
	Session session = null;
	Transaction transaction = null;
	try {
		session = getSession();
		transaction = session.beginTransaction();

		String hql = "select count(*) from SbiDataSetFederation s where s.id.dsId = ? ";
		Query aQuery = session.createQuery(hql);
		aQuery.setInteger(0, dsId.intValue());
		resultNumber = new Integer(((Long) aQuery.uniqueResult()).intValue());

	} catch (Throwable t) {
		if (transaction != null && transaction.isActive()) {
			transaction.rollback();
		}
		throw new SpagoBIDAOException("Error while counting the federations associated with the data set with id " + dsId, t);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return resultNumber;

}
 
Example 14
/**
 * Load table column by name.
 *
 * @param name
 *            the table column name
 * @param tableId
 *            the table id
 * @return the meta table column
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.metadata.dao.ISbiMetaTableColumnDAOHibImpl#loadTableByName(string)
 */
@Override
public SbiMetaTableColumn loadTableColumnByNameAndTable(String name, Integer tableId) throws EMFUserError {
	logger.debug("IN");

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

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

		toReturn = loadTableColumnByNameAndTable(tmpSession, name, tableId);
		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 15
/**
 * Load viewpoint by id.
 *
 * @param id
 *            the id
 *
 * @return the viewpoint
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.analiticalmodel.document.dao.IMetaModelViewpointDAO#loadViewpointByID(java.lang.Integer)
 */
@Override
public Viewpoint loadViewpointByID(Integer id) throws EMFUserError {
	Viewpoint toReturn = null;
	Session aSession = null;
	Transaction tx = null;

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

		SbiMetaModelViewpoints hibViewpoint = (SbiMetaModelViewpoints) aSession.load(SbiMetaModelViewpoints.class, id);

		toReturn = toMetaModelViewpoint(hibViewpoint);
		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 toReturn;
}
 
Example 16
Source Project: tutorials   File: FooFixtures.java    License: MIT License 5 votes vote down vote up
public void createBars() {
    Session session = null;
    Transaction tx = null;
    session = sessionFactory.openSession();
    tx = session.getTransaction();
    try {
        tx.begin();
        for (int i = 156; i < 160; i++) {
            final Bar bar = new Bar();
            bar.setName("Bar_" + i);
            final Foo foo = new Foo("Foo_" + (i + 120));
            foo.setBar(bar);
            session.save(foo);
            final Foo foo2 = new Foo(null);
            if (i % 2 == 0)
                foo2.setName("LuckyFoo" + (i + 120));
            foo2.setBar(bar);
            session.save(foo2);
            bar.getFooSet().add(foo);
            bar.getFooSet().add(foo2);
            session.merge(bar);
        }
        tx.commit();
        session.flush();
    } catch (final HibernateException he) {
        if (tx != null)
            tx.rollback();
        System.out.println("Not able to open session");
        he.printStackTrace();
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null)
            session.close();
    }

}
 
Example 17
/**
 * Load parameters use by par id.
 *
 * @param parId
 *            the par id
 *
 * @return the list
 *
 * @throws EMFUserError
 *             the EMF user error
 *
 * @see it.eng.spagobi.behaviouralmodel.analyticaldriver.dao.IParameterUseDAO#loadParametersUseByParId(java.lang.Integer)
 */
@Override
public List loadParametersUseByParId(Integer parId) throws EMFUserError {
	List realResult = new ArrayList();

	Session aSession = null;
	Transaction tx = null;

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

		// String hql = "from SbiParuse s where s.sbiParameters.parId="+parId;
		String hql = "from SbiParuse s where s.sbiParameters.parId=? ";
		Query query = aSession.createQuery(hql);
		query.setInteger(0, parId.intValue());
		List result = query.list();

		Iterator it = result.iterator();
		while (it.hasNext()) {
			realResult.add(toParameterUse((SbiParuse) it.next(), true));
		}

		tx.commit();

	} catch (HibernateException he) {

		logException(he);

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

		logger.error("HibernateException", he);

		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);

	} finally {

		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
		}

	}

	return realResult;
}
 
Example 18
Source Project: unitime   File: BuildingsConntector.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void doDelete(ApiHelper helper) throws IOException {
	Transaction tx = helper.getHibSession().beginTransaction();
	try {
		Building building = null;
		Long buildingId = helper.getOptinalParameterLong("id", null);
		if (buildingId != null) {
			building = BuildingDAO.getInstance().get(buildingId, helper.getHibSession());
			if (building == null)
				throw new IllegalArgumentException("Building " + buildingId + " does not exist.");
		} else {
			Long sessionId = helper.getAcademicSessionId();
			if (sessionId == null)
				throw new IllegalArgumentException("Academic session not provided, please set the term parameter.");
			String externalId = helper.getOptinalParameter("externalId", null);
			if (externalId != null) {
				building = (Building)helper.getHibSession().createQuery("from Building where externalUniqueId = :externalId and session.uniqueId = :sessionId")
						.setLong("sessionId", sessionId).setString("externalId", externalId).setMaxResults(1).uniqueResult();
				if (building == null)
					throw new IllegalArgumentException("Building " + externalId + " does not exist.");
			}
			if (building == null) {
				String abbv = helper.getRequiredParameter("building");
				building = (Building)helper.getHibSession().createQuery("from Building where (abbreviation = :abbv or name = :abbv) and session.uniqueId = :sessionId")
						.setLong("sessionId", sessionId).setString("abbv", abbv).setMaxResults(1).uniqueResult();
				if (building == null)
					throw new IllegalArgumentException("Building " + abbv + " does not exist.");
			}
		}
		helper.getSessionContext().checkPermissionAnyAuthority(building.getSession(), Right.ApiRoomEdit);
		helper.getSessionContext().checkPermissionAnyAuthority(building, Right.BuildingDelete);
		
		for (Room r: (List<Room>)BuildingDAO.getInstance().getSession().createQuery("from Room r where r.building.uniqueId = :buildingId").setLong("buildingId", building.getUniqueId()).list()) {
			helper.getHibSession().createQuery("delete RoomPref p where p.room.uniqueId = :roomId").setLong("roomId", r.getUniqueId()).executeUpdate();
			for (Iterator<Assignment> i = r.getAssignments().iterator(); i.hasNext(); ) {
				Assignment a = i.next();
                   a.getRooms().remove(r);
                   helper.getHibSession().saveOrUpdate(a);
                   i.remove();
               }
			helper.getHibSession().delete(r);
		}
		ChangeLog.addChange(
                   helper.getHibSession(),
                   TimetableManager.findByExternalId(sessionContext.getUser().getExternalUserId()),
                   building.getSession(),
                   building, 
                   ChangeLog.Source.BUILDING_EDIT, 
                   ChangeLog.Operation.DELETE, 
                   null, 
                   null);
		helper.getHibSession().delete(building);
		tx.commit();
	} catch (Exception e) {
		if (tx != null) { tx.rollback(); }
		if (e instanceof RuntimeException) throw (RuntimeException)e;
		if (e instanceof IOException) throw (IOException)e;
		throw new IOException(e.getMessage(), e);
	}
}
 
Example 19
@Override
public List<ProgressThread> loadNotClosedProgressThreadsByUserId(String userId) throws EMFUserError {
	// logger.debug("IN");
	List<ProgressThread> toReturn = null;

	Session aSession = null;
	Transaction tx = null;

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

		Query hibPT = aSession.createQuery("from SbiProgressThread h where h.userId = ? AND h.status != 'CLOSED'");
		hibPT.setString(0, userId);

		List sbiProgressThreadList = hibPT.list();
		if (sbiProgressThreadList != null) {
			toReturn = new ArrayList<ProgressThread>();
			for (Iterator iterator = sbiProgressThreadList.iterator(); iterator.hasNext();) {
				SbiProgressThread sbiPT = (SbiProgressThread) iterator.next();
				ProgressThread pT = toProgressThread(sbiPT);
				toReturn.add(pT);
			}
		}

		tx.commit();

	} catch (HibernateException he) {
		logger.error("Error while loading Progress Threads with userId" + userId + " and status NOT CLOSED", he);
		if (tx != null)
			tx.rollback();
		throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
	} finally {
		if (aSession != null) {
			if (aSession.isOpen())
				aSession.close();
			// logger.debug("OUT");
		}
	}
	// logger.debug("OUT");
	return toReturn;
}
 
Example 20
public void createCheckedObjectMap(SourceBean request) throws Exception {
		checkedObjectsMap = new HashMap();

		// get CHECKED_QUERY query parameters

		String[] parameters = getQueryParameters("CHECKED_QUERY", request);

		// get CHECKED_QUERY statment
		String statement = getQueryStatement("CHECKED_QUERY", parameters);

		Session aSession = null;
		Transaction tx = null;
		
		// exec CHECKED_QUERY
		ScrollableDataResult scrollableDataResult = null;
		SQLCommand sqlCommand = null;
		DataConnection dataConnection = null;
		DataResult dataResult = null;
		try {
			aSession = HibernateSessionManager.getCurrentSession();
			tx = aSession.beginTransaction();
			//Connection jdbcConnection = aSession.connection();
			Connection jdbcConnection = HibernateSessionManager.getConnection(aSession);
			dataConnection = DelegatedHibernateConnectionListService.getDataConnection(jdbcConnection);
        	sqlCommand = dataConnection.createSelectCommand(statement);
        	dataResult = sqlCommand.execute();
        	scrollableDataResult = (ScrollableDataResult) dataResult.getDataObject();
			SourceBean chekedObjectsBean = scrollableDataResult.getSourceBean();
			List checkedObjectsList = chekedObjectsBean
					.getAttributeAsList("ROW");
			for (int i = 0; i < checkedObjectsList.size(); i++) {
				SourceBean objects = (SourceBean) checkedObjectsList.get(i);
				String key = getObjectKey(objects);
				checkedObjectsMap.put(key, key);
			}
			
//			aSession.doWork(new MyWork(statement));
			
//			tx.commit();
		} catch (HibernateException he) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, 
		            this.getClass().getName(), 
		            "execCheckedQuery", 
		            he.getMessage());
			if (tx != null)
				tx.rollback();
			throw new EMFUserError(EMFErrorSeverity.ERROR, 100);
		} catch (Exception e) {
			SpagoBITracer.major(SpagoBIConstants.NAME_MODULE, this.getClass()
					.getName(), "createCheckedObjectMap", e.getMessage(), e);
		} finally {
			if (aSession != null) {
				if (aSession.isOpen()) aSession.close();
			}
		}
	}