javax.persistence.TransactionRequiredException Java Examples

The following examples show how to use javax.persistence.TransactionRequiredException. 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: ApplicationManagedEntityManagerIntegrationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCannotFlushWithoutGettingTransaction() {
	EntityManager em = entityManagerFactory.createEntityManager();
	try {
		doInstantiateAndSave(em);
		fail("Should have thrown TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}

	// TODO following lines are a workaround for Hibernate bug
	// If Hibernate throws an exception due to flush(),
	// it actually HAS flushed, meaning that the database
	// was updated outside the transaction
	deleteAllPeopleUsingEntityManager(sharedEntityManager);
	setComplete();
}
 
Example #2
Source File: JtaEntityManagerRegistry.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void transactionStarted(final InstanceId instanceId) {
    if (instanceId == null) {
        throw new NullPointerException("instanceId is null");
    }
    if (!isTransactionActive()) {
        throw new TransactionRequiredException();
    }

    final Map<EntityManagerFactory, EntityManagerTracker> entityManagers = entityManagersByDeploymentId.get(instanceId);
    if (entityManagers == null) {
        return;
    }

    for (final Map.Entry<EntityManagerFactory, EntityManagerTracker> entry : entityManagers.entrySet()) {
        final EntityManagerFactory entityManagerFactory = entry.getKey();
        final EntityManagerTracker value = entry.getValue();
        final EntityManager entityManager = value.getEntityManager();
        if (value.autoJoinTx) {
            entityManager.joinTransaction();
        }
        final EntityManagerTxKey txKey = new EntityManagerTxKey(entityManagerFactory);
        transactionRegistry.putResource(txKey, entityManager);
    }
}
 
Example #3
Source File: ApplicationManagedEntityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
public void testCannotFlushWithoutGettingTransaction() {
	EntityManager em = entityManagerFactory.createEntityManager();
	try {
		doInstantiateAndSave(em);
		fail("Should have thrown TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}

	// TODO following lines are a workaround for Hibernate bug
	// If Hibernate throws an exception due to flush(),
	// it actually HAS flushed, meaning that the database
	// was updated outside the transaction
	deleteAllPeopleUsingEntityManager(sharedEntityManager);
	setComplete();
}
 
Example #4
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private void joinTransaction(boolean explicitRequest) {
	if ( !getTransactionCoordinator().getTransactionCoordinatorBuilder().isJta() ) {
		if ( explicitRequest ) {
			log.callingJoinTransactionOnNonJtaEntityManager();
		}
		return;
	}

	try {
		getTransactionCoordinator().explicitJoin();
	}
	catch (TransactionRequiredForJoinException e) {
		throw new TransactionRequiredException( e.getMessage() );
	}
	catch (HibernateException he) {
		throw exceptionConverter.convert( he );
	}
}
 
Example #5
Source File: ApplicationManagedEntityManagerIntegrationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCannotFlushWithoutGettingTransaction() {
	EntityManager em = entityManagerFactory.createEntityManager();
	try {
		doInstantiateAndSave(em);
		fail("Should have thrown TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}

	// TODO following lines are a workaround for Hibernate bug
	// If Hibernate throws an exception due to flush(),
	// it actually HAS flushed, meaning that the database
	// was updated outside the transaction
	deleteAllPeopleUsingEntityManager(sharedEntityManager);
	setComplete();
}
 
Example #6
Source File: AbstractProducedQuery.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected List<R> doList() {
	if ( getMaxResults() == 0 ) {
		return Collections.EMPTY_LIST;
	}
	if ( lockOptions.getLockMode() != null && lockOptions.getLockMode() != LockMode.NONE ) {
		if ( !getProducer().isTransactionInProgress() ) {
			throw new TransactionRequiredException( "no transaction is in progress" );
		}
	}

	final String expandedQuery = getQueryParameterBindings().expandListValuedParameters( getQueryString(), getProducer() );
	return getProducer().list(
			expandedQuery,
			makeQueryParametersForExecution( expandedQuery )
	);
}
 
Example #7
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public LockModeType getLockMode(Object entity) {
	checkOpen();

	if ( !isTransactionInProgress() ) {
		throw new TransactionRequiredException( "Call to EntityManager#getLockMode should occur within transaction according to spec" );
	}

	if ( !contains( entity ) ) {
		throw exceptionConverter.convert( new IllegalArgumentException( "entity not in the persistence context" ) );
	}

	return LockModeTypeHelper.getLockModeType( getCurrentLockMode( entity ) );

}
 
Example #8
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(Object entity) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.remove(entity);
    }
}
 
Example #9
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void flush() {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.flush();
    }
}
 
Example #10
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void lock(Object entity, LockModeType lockMode) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.lock(entity, lockMode);
    }
}
 
Example #11
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void lock(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.lock(entity, lockMode, properties);
    }
}
 
Example #12
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void refresh(Object entity, Map<String, Object> properties) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.refresh(entity, properties);
    }
}
 
Example #13
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void refresh(Object entity, LockModeType lockMode) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.refresh(entity, lockMode);
    }
}
 
Example #14
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void refresh(Object entity, LockModeType lockMode, Map<String, Object> properties) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.refresh(entity, lockMode, properties);
    }
}
 
Example #15
Source File: EntityManagerSessionImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void flush() {
  if (entityManager != null && (!handleTransactions || isTransactionActive()) ) {
    try {
      entityManager.flush();
    } catch (IllegalStateException ise) {
      throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
    } catch (TransactionRequiredException tre) {
      throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
    } catch (PersistenceException pe) {
      throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
    }
  }
}
 
Example #16
Source File: EntityManagerSessionImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public void flush() {
  if (entityManager != null && (!handleTransactions || isTransactionActive())) {
    try {
      entityManager.flush();
    } catch (IllegalStateException ise) {
      throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
    } catch (TransactionRequiredException tre) {
      throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
    } catch (PersistenceException pe) {
      throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
    }
  }
}
 
Example #17
Source File: ExtendedEntityManagerCreator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Join an existing transaction, if not already joined.
 * @param enforce whether to enforce the transaction
 * (i.e. whether failure to join is considered fatal)
 */
private void doJoinTransaction(boolean enforce) {
	if (this.jta) {
		// Let's try whether we're in a JTA transaction.
		try {
			this.target.joinTransaction();
			logger.debug("Joined JTA transaction");
		}
		catch (TransactionRequiredException ex) {
			if (!enforce) {
				logger.debug("No JTA transaction to join: " + ex);
			}
			else {
				throw ex;
			}
		}
	}
	else {
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			if (!TransactionSynchronizationManager.hasResource(this.target) &&
					!this.target.getTransaction().isActive()) {
				enlistInCurrentTransaction();
			}
			logger.debug("Joined local transaction");
		}
		else {
			if (!enforce) {
				logger.debug("No local transaction to join");
			}
			else {
				throw new TransactionRequiredException("No local transaction to join");
			}
		}
	}
}
 
Example #18
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void refresh(Object entity) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.refresh(entity);
    }
}
 
Example #19
Source File: ProcedureCallImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public int executeUpdate() {
	if ( ! getProducer().isTransactionInProgress() ) {
		throw new TransactionRequiredException( "javax.persistence.Query.executeUpdate requires active transaction" );
	}

	// the expectation is that there is just one Output, of type UpdateCountOutput
	try {
		execute();
		return getUpdateCount();
	}
	finally {
		outputs().release();
	}
}
 
Example #20
Source File: ExtendedEntityManagerCreator.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Join an existing transaction, if not already joined.
 * @param enforce whether to enforce the transaction
 * (i.e. whether failure to join is considered fatal)
 */
private void doJoinTransaction(boolean enforce) {
	if (this.jta) {
		// Let's try whether we're in a JTA transaction.
		try {
			this.target.joinTransaction();
			logger.debug("Joined JTA transaction");
		}
		catch (TransactionRequiredException ex) {
			if (!enforce) {
				logger.debug("No JTA transaction to join: " + ex);
			}
			else {
				throw ex;
			}
		}
	}
	else {
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			if (!TransactionSynchronizationManager.hasResource(this.target) &&
					!this.target.getTransaction().isActive()) {
				enlistInCurrentTransaction();
			}
			logger.debug("Joined local transaction");
		}
		else {
			if (!enforce) {
				logger.debug("No local transaction to join");
			}
			else {
				throw new TransactionRequiredException("No local transaction to join");
			}
		}
	}
}
 
Example #21
Source File: EntityManagerFactoryUtilsTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
	EntityNotFoundException entityNotFound = new EntityNotFoundException();
	assertSame(JpaObjectRetrievalFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

	NoResultException noResult = new NoResultException();
	assertSame(EmptyResultDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

	NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
	assertSame(IncorrectResultSizeDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

	OptimisticLockException optimisticLock = new OptimisticLockException();
	assertSame(JpaOptimisticLockingFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

	EntityExistsException entityExists = new EntityExistsException("foo");
	assertSame(DataIntegrityViolationException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

	TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
	assertSame(InvalidDataAccessApiUsageException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());

	PersistenceException unknown = new PersistenceException() {
	};
	assertSame(JpaSystemException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
 
Example #22
Source File: ContainerManagedEntityManagerIntegrationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
	try {
		createContainerManagedEntityManager().joinTransaction();
		fail("Should have thrown a TransactionRequiredException");
	}
	catch (TransactionRequiredException e) {
		/* expected */
	}
}
 
Example #23
Source File: EntityManagerSessionImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new FlowableException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new FlowableException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new FlowableException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
 
Example #24
Source File: EntityManagerSessionImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@Override
public void flush() {
    if (entityManager != null && (!handleTransactions || isTransactionActive())) {
        try {
            entityManager.flush();
        } catch (IllegalStateException ise) {
            throw new ActivitiException("Error while flushing EntityManager, illegal state", ise);
        } catch (TransactionRequiredException tre) {
            throw new ActivitiException("Cannot flush EntityManager, an active transaction is required", tre);
        } catch (PersistenceException pe) {
            throw new ActivitiException("Error while flushing EntityManager: " + pe.getMessage(), pe);
        }
    }
}
 
Example #25
Source File: EntityManagerSessionImpl.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
public void flush() {
  if (entityManager != null && (!handleTransactions || isTransactionActive()) ) {
    try {
      entityManager.flush();
    } catch (IllegalStateException ise) {
      throw new ProcessEngineException("Error while flushing EntityManager, illegal state", ise);
    } catch (TransactionRequiredException tre) {
      throw new ProcessEngineException("Cannot flush EntityManager, an active transaction is required", tre);
    } catch (PersistenceException pe) {
      throw new ProcessEngineException("Error while flushing EntityManager: " + pe.getMessage(), pe);
    }
  }
}
 
Example #26
Source File: TransactionScopedEntityManager.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public void persist(Object entity) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.persist(entity);
    }
}
 
Example #27
Source File: ExtendedEntityManagerCreator.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Join an existing transaction, if not already joined.
 * @param enforce whether to enforce the transaction
 * (i.e. whether failure to join is considered fatal)
 */
private void doJoinTransaction(boolean enforce) {
	if (this.jta) {
		// Let's try whether we're in a JTA transaction.
		try {
			this.target.joinTransaction();
			logger.debug("Joined JTA transaction");
		}
		catch (TransactionRequiredException ex) {
			if (!enforce) {
				logger.debug("No JTA transaction to join: " + ex);
			}
			else {
				throw ex;
			}
		}
	}
	else {
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			if (!TransactionSynchronizationManager.hasResource(this.target) &&
					!this.target.getTransaction().isActive()) {
				enlistInCurrentTransaction();
			}
			logger.debug("Joined local transaction");
		}
		else {
			if (!enforce) {
				logger.debug("No local transaction to join");
			}
			else {
				throw new TransactionRequiredException("No local transaction to join");
			}
		}
	}
}
 
Example #28
Source File: EntityManagerFactoryUtilsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void testConvertJpaPersistenceException() {
	EntityNotFoundException entityNotFound = new EntityNotFoundException();
	assertSame(JpaObjectRetrievalFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityNotFound).getClass());

	NoResultException noResult = new NoResultException();
	assertSame(EmptyResultDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(noResult).getClass());

	NonUniqueResultException nonUniqueResult = new NonUniqueResultException();
	assertSame(IncorrectResultSizeDataAccessException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(nonUniqueResult).getClass());

	OptimisticLockException optimisticLock = new OptimisticLockException();
	assertSame(JpaOptimisticLockingFailureException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(optimisticLock).getClass());

	EntityExistsException entityExists = new EntityExistsException("foo");
	assertSame(DataIntegrityViolationException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(entityExists).getClass());

	TransactionRequiredException transactionRequired = new TransactionRequiredException("foo");
	assertSame(InvalidDataAccessApiUsageException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(transactionRequired).getClass());

	PersistenceException unknown = new PersistenceException() {
	};
	assertSame(JpaSystemException.class,
			EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(unknown).getClass());
}
 
Example #29
Source File: ContainerManagedEntityManagerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
	endTransaction();

	try {
		createContainerManagedEntityManager().joinTransaction();
		fail("Should have thrown a TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}
}
 
Example #30
Source File: ExtendedEntityManagerCreator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Join an existing transaction, if not already joined.
 * @param enforce whether to enforce the transaction
 * (i.e. whether failure to join is considered fatal)
 */
private void doJoinTransaction(boolean enforce) {
	if (this.jta) {
		// Let's try whether we're in a JTA transaction.
		try {
			this.target.joinTransaction();
			logger.debug("Joined JTA transaction");
		}
		catch (TransactionRequiredException ex) {
			if (!enforce) {
				logger.debug("No JTA transaction to join: " + ex);
			}
			else {
				throw ex;
			}
		}
	}
	else {
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			if (!TransactionSynchronizationManager.hasResource(this.target) &&
					!this.target.getTransaction().isActive()) {
				enlistInCurrentTransaction();
			}
			logger.debug("Joined local transaction");
		}
		else {
			if (!enforce) {
				logger.debug("No local transaction to join");
			}
			else {
				throw new TransactionRequiredException("No local transaction to join");
			}
		}
	}
}