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

The following examples show how to use org.hibernate.Transaction#isActive() . 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: UdpDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public void delete(SbiUdp prop) {
	logger.debug("IN");
	Session session = getSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		session.delete(prop);
		tx.commit();

	} catch (HibernateException e) {
		if( tx != null && tx.isActive() ){
			tx.rollback();
		}
		throw e;

	}finally{
		session.close();
	}
	logger.debug("OUT");
}
 
Example 2
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.isActive())
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example 3
Source File: SbiFederationDefinitionDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
private int saveSbiFederationDefinition(FederationDefinition dataset, boolean duplicated) {
	LogMF.debug(logger, "IN:  model = [{0}]", dataset);

	Session session = null;
	Transaction transaction = null;

	try {
		session = getSession();
		Assert.assertNotNull(session, "session cannot be null");
		transaction = session.beginTransaction();
		int id = saveSbiFederationDefinition(dataset, duplicated, session, transaction).getFederation_id();
		transaction.commit();
		return id;
	} catch (Throwable t) {
		logException(t);
		if (transaction != null && transaction.isActive()) {
			transaction.rollback();
		}
		throw new SpagoBIDAOException("An unexpected error occured while saving model [" + dataset + "]", t);
	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
	}

}
 
Example 4
Source File: CacheHibernateStoreSessionListener.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
        try {
            Transaction tx = hibSes.getTransaction();

            if (commit) {
                hibSes.flush();

                if (tx.isActive())
                    tx.commit();
            }
            else if (tx.isActive())
                tx.rollback();
        }
        catch (HibernateException e) {
            throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
        }
        finally {
            hibSes.close();
        }
    }
}
 
Example 5
Source File: AbstractConnectionProviderTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    Session session = null;
    Transaction txn = null;
    try {
        session = sf.openSession();
        txn = session.beginTransaction();

        SecurityId securityId = new SecurityId();
        securityId.setRole("Role");
        session.persist(securityId);

        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}
 
Example 6
Source File: AbstractTest.java    From hibernate-master-class with Apache License 2.0 6 votes vote down vote up
protected void doInTransaction(HibernateTransactionConsumer callable) {
    Session session = null;
    Transaction txn = null;
    try {
        session = getSessionFactory().openSession();
        callable.beforeTransactionCompletion();
        txn = session.beginTransaction();

        callable.accept(session);
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        callable.afterTransactionCompletion();
        if (session != null) {
            session.close();
        }
    }
}
 
Example 7
Source File: UdpValueDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Integer insert(SbiUdpValue propValue) {
	logger.debug("IN");
	Session session = null;
	Transaction tx = null;
	Integer id = null;
	try {
		session = getSession();
		tx = session.beginTransaction();
		updateSbiCommonInfo4Insert(propValue);
		id = (Integer) session.save(propValue);
		tx.commit();
	} catch (HibernateException e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
		}
		throw e;
	} finally {
		if (session != null) {
			session.close();
		}
		logger.debug("OUT");
	}
	return id;
}
 
Example 8
Source File: UdpValueDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void update(SbiUdpValue propValue) {
	logger.debug("IN");
	Session session = getSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		updateSbiCommonInfo4Update(propValue);
		session.update(propValue);
		tx.commit();

	} catch (HibernateException e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
		}
		throw e;

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

}
 
Example 9
Source File: UdpValueDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public SbiUdpValue findById(Integer id) {
	logger.debug("IN");
	SbiUdpValue propValue = null;
	Session session = getSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();
		propValue = (SbiUdpValue) session.get(SbiUdpValue.class, id);
		tx.commit();
	} catch (HibernateException e) {
		if (tx != null && tx.isActive()) {
			tx.rollback();
		}
		throw e;

	} finally {
		session.close();
	}
	logger.debug("OUT");
	return propValue;
}
 
Example 10
Source File: UdpDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<SbiUdp> findAll() {
	Session session = getSession();
	Transaction tx = null;
	try {
		tx = session.beginTransaction();

		List<SbiUdp> list = (List<SbiUdp>)session.createQuery("from SbiUdp").list();
		tx.commit();
		return list;

	} catch (HibernateException e) {
		if( tx != null && tx.isActive() ){
			tx.rollback();
		}
		throw e;

	}finally{
		session.close();
	}
}
 
Example 11
Source File: CatalogFunctionDAOImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public SbiCatalogFunction getCatalogFunctionByLabel(String label) {

    Session session;
    Transaction transaction = null;
    SbiCatalogFunction sbiCatalogFunction = null;

    logger.debug("IN");

    session = null;
    try {

        session = getSession();
        Assert.assertNotNull(session, "session cannot be null");
        transaction = session.beginTransaction();

        String hql = "FROM SbiCatalogFunction F WHERE F.label = ?";
        Query query = session.createQuery(hql);
        query.setString(0, label);
        sbiCatalogFunction = (SbiCatalogFunction) query.uniqueResult();

        transaction.commit();

    } catch (Throwable t) {
        if (transaction != null && transaction.isActive()) {
            transaction.rollback();
        }
        throw new SpagoBIDAOException("An error occured while reading Catalog Functions from DB", t);

    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
        logger.debug("OUT");
    }
    return sbiCatalogFunction;

}
 
Example 12
Source File: CacheDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public List<CacheItem> loadAllCacheItems() {
	logger.debug("IN");

	List<CacheItem> toReturn = new ArrayList<CacheItem>();
	Session session = null;
	Transaction transaction = null;
	try {
		session = getSession();
		transaction = session.beginTransaction();

		Query hibQuery = session.createQuery("from SbiCacheItem");
		List hibList = hibQuery.list();
		Iterator it = hibList.iterator();
		while (it.hasNext()) {
			SbiCacheItem hibMap = (SbiCacheItem) it.next();
			if (hibMap != null) {
				CacheItem cacheItem = toCacheItem(hibMap);
				toReturn.add(cacheItem);
			}
		}
		transaction.commit();
	} catch (Throwable t) {
		if (transaction != null && transaction.isActive()) {
			transaction.rollback();
		}
		throw new SpagoBIDAOException("An unexpected error occured while loading all cache items", t);

	} finally {
		if (session != null && session.isOpen()) {
			session.close();
		}
		logger.debug("OUT");
	}
	return toReturn;
}
 
Example 13
Source File: SpringTransactionFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isTransactionInProgress(
		JDBCContext jdbcContext, Context transactionContext, Transaction transaction) {

	return (transaction != null && transaction.isActive()) ||
			TransactionSynchronizationManager.isActualTransactionActive();
}
 
Example 14
Source File: SbiFederationDefinitionDAOHibImpl.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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 15
Source File: AbstractHibernateDAO.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public void commitIfActiveAndClose(Transaction tx, Session aSession) {
	if (tx != null && tx.isActive()) {
		tx.commit();
	}
	if (aSession != null && aSession.isOpen()) {
		aSession.close();
	}
}
 
Example 16
Source File: WorldResource.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
		ExecutionException {
	final int queries = getQueries(queriesParam);
	final World[] worlds = new World[queries];

	Callable<World[]> callable = () -> {
		Session session = emf.createEntityManager().unwrap(Session.class);
		session.setDefaultReadOnly(false);
		Transaction txn = session.beginTransaction();

		try {
			// using write batching. See the data source properties provided
			// in the configuration file

			// 1. Read and update the entities from the DB
			for (int i = 0; i < queries; i++) {
				final World world = (World) session.byId(World.class).load(randomWorld());
				world.setRandomNumber(randomWorld());
				worlds[i] = world;
			}

			// 2. Sort the array to prevent transaction deadlock in the DB
			Arrays.sort(worlds, Comparator.comparingInt(World::getId));

			// 3. Actually save the entities
			for (int i = 0; i < worlds.length; i++) {
				session.persist(worlds[i]);
			}

			session.flush();
			session.clear();
			txn.commit();

			return worlds;
		} catch (RuntimeException e) {
			if (txn != null && txn.isActive())
				txn.rollback();
			throw e;
		} finally {
			session.close();
		}
	};
	Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
	return futureWorlds.get();
}
 
Example 17
Source File: ExamDistributionPrefsAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
  * Delete distribution pref
  * @param distPrefId
  */
 private void doDelete(HttpServletRequest request, String distPrefId) {
     Transaction tx = null;
     
     sessionContext.checkPermission(distPrefId, "DistributionPref", Right.ExaminationDistributionPreferenceDelete);

     try {
         
      DistributionPrefDAO dpDao = new DistributionPrefDAO();
      org.hibernate.Session hibSession = dpDao.getSession();
      tx = hibSession.getTransaction();
      if (tx==null || !tx.isActive())
          tx = hibSession.beginTransaction();
      
         HashSet relatedExams = new HashSet();
      DistributionPref dp = dpDao.get(new Long(distPrefId));
      PreferenceGroup owner = (PreferenceGroup) dp.getOwner();
      owner.getPreferences().remove(dp);
for (Iterator i=dp.getDistributionObjects().iterator();i.hasNext();) {
	DistributionObject dObj = (DistributionObject)i.next();
	PreferenceGroup pg = dObj.getPrefGroup();
	relatedExams.add(pg);
	pg.getDistributionObjects().remove(dObj);
	hibSession.saveOrUpdate(pg);
}
      
      hibSession.delete(dp);
      hibSession.saveOrUpdate(owner);
      
         for (Iterator i=relatedExams.iterator();i.hasNext();) {
             Exam exam = (Exam)i.next();
             ChangeLog.addChange(
                     hibSession, 
                     sessionContext, 
                     exam, 
                     ChangeLog.Source.DIST_PREF_EDIT,
                     ChangeLog.Operation.DELETE,
                     exam.firstSubjectArea(), 
                     exam.firstDepartment());
         }

         if (tx!=null && tx.isActive()) 
          tx.commit();
      
      hibSession.flush();
      hibSession.refresh(owner);
     }
     catch (Exception e) {
         Debug.error(e);
         if (tx!=null && tx.isActive()) 
             tx.rollback();
     }
 }
 
Example 18
Source File: RoomFeatureEditAction.java    From unitime with Apache License 2.0 4 votes vote down vote up
/**
 * 
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return
 * @throws HibernateException
 */
public ActionForward deleteRoomFeature(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	RoomFeatureEditForm roomFeatureEditForm = (RoomFeatureEditForm) form;
	Long id = new Long(roomFeatureEditForm.getId());
	RoomFeatureDAO rdao = new RoomFeatureDAO();
	org.hibernate.Session hibSession = rdao.getSession();
	Transaction tx = null;
	try {
		tx = hibSession.beginTransaction();
		
		RoomFeature rf = rdao.get(id, hibSession);
		
		if (rf != null) {
			
			sessionContext.checkPermission(rf, rf instanceof GlobalRoomFeature ? Right.GlobalRoomFeatureDelete : Right.DepartmenalRoomFeatureDelete);
               
               ChangeLog.addChange(
                       hibSession, 
                       sessionContext, 
                       rf, 
                       ChangeLog.Source.ROOM_FEATURE_EDIT, 
                       ChangeLog.Operation.DELETE, 
                       null, 
                       (rf instanceof DepartmentRoomFeature?((DepartmentRoomFeature)rf).getDepartment():null));

               for (Iterator i=rf.getRooms().iterator();i.hasNext();) {
				Location loc = (Location)i.next();
				loc.getFeatures().remove(rf);
				hibSession.save(loc);
			}
               
			for (RoomFeaturePref p: (List<RoomFeaturePref>)hibSession.createQuery("from RoomFeaturePref p where p.roomFeature.uniqueId = :id")
					.setLong("id", id).list()) {
				p.getOwner().getPreferences().remove(p);
				hibSession.delete(p);
				hibSession.saveOrUpdate(p.getOwner());
			}
               
			hibSession.delete(rf);
		}
           
		tx.commit();
	} catch (Exception e) {
		if (tx!=null && tx.isActive()) tx.rollback();
		throw e;
	}
		
	roomFeatureEditForm.setDeptCode((String)sessionContext.getAttribute(SessionAttribute.DepartmentCodeRoom));
	return mapping.findForward("showRoomFeatureList");
}
 
Example 19
Source File: WorldResource.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@GET
@Path("/updates")
public World[] updates(@QueryParam("queries") String queriesParam) throws InterruptedException,
		ExecutionException {
	final int queries = getQueries(queriesParam);
	final World[] worlds = new World[queries];

	Callable<World[]> callable = () -> {
		Session session = emf.createEntityManager().unwrap(Session.class);
		session.setDefaultReadOnly(false);
		Transaction txn = session.beginTransaction();

		try {
			// using write batching. See the data source properties provided
			// in the configuration file

			// 1. Read and update the entities from the DB
	        final AtomicInteger ii = new AtomicInteger(0);
	        ThreadLocalRandom.current().ints(1, 10001).distinct().limit(queries).forEach(
	            (randomValue)->{
	            		final World world = (World) session.byId(World.class).load(randomValue);
	            		world.setRandomNumber(randomWorld());
	            		worlds[ii.getAndAdd(1)]=world;
	            	}
	        );

	        // 2. Sort the array to prevent transaction deadlock in the DB
			Arrays.sort(worlds, Comparator.comparingInt(World::getId));

			// 3. Actually save the entities
			for (int i = 0; i < worlds.length; i++) {
				session.persist(worlds[i]);
			}

			session.flush();
			session.clear();
			txn.commit();

			return worlds;
		} catch (RuntimeException e) {
			if (txn != null && txn.isActive())
				txn.rollback();
			throw e;
		} finally {
			session.close();
		}
	};
	Future<World[]> futureWorlds = Common.EXECUTOR.submit(callable);
	return futureWorlds.get();
}
 
Example 20
Source File: UnitOfWork.java    From commafeed with Apache License 2.0 4 votes vote down vote up
private static void rollbackTransaction(Session session) {
	final Transaction txn = session.getTransaction();
	if (txn != null && txn.isActive()) {
		txn.rollback();
	}
}