类javax.persistence.TransactionRequiredException源码实例Demo

下面列出了怎么用javax.persistence.TransactionRequiredException的API类实例代码及写法,或者点击链接到github查看源代码。

@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();
}
 
@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();
}
 
源代码3 项目: lams   文件: AbstractProducedQuery.java
@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 )
	);
}
 
源代码4 项目: lams   文件: SessionImpl.java
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 );
	}
}
 
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();
}
 
源代码6 项目: tomee   文件: JtaEntityManagerRegistry.java
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);
    }
}
 
/**
 * 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");
			}
		}
	}
}
 
@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());
}
 
@Test
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
	endTransaction();

	try {
		createContainerManagedEntityManager().joinTransaction();
		fail("Should have thrown a TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}
}
 
/**
 * 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");
			}
		}
	}
}
 
@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());
}
 
@Test
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
	endTransaction();

	try {
		createContainerManagedEntityManager().joinTransaction();
		fail("Should have thrown a TransactionRequiredException");
	}
	catch (TransactionRequiredException ex) {
		// expected
	}
}
 
源代码13 项目: quarkus   文件: NoTransactionTest.java
@Test
public void testNTransaction() {
    Arc.container().requestContext().activate();
    try {
        Assertions.assertThrows(TransactionRequiredException.class, () -> {
            Address a = new Address("test");
            entityManager.persist(a);
        });
    } finally {
        Arc.container().requestContext().terminate();
    }
}
 
源代码14 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码15 项目: quarkus   文件: TransactionScopedEntityManager.java
@Override
public <T> T merge(T entity) {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        return emr.em.merge(entity);
    }
}
 
源代码16 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码17 项目: quarkus   文件: TransactionScopedEntityManager.java
@Override
public void flush() {
    checkBlocking();
    try (EntityManagerResult emr = getEntityManager()) {
        if (!emr.allowModification) {
            throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
        }
        emr.em.flush();
    }
}
 
源代码18 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码19 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码20 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码21 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码22 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码23 项目: quarkus   文件: TransactionScopedEntityManager.java
@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);
    }
}
 
源代码24 项目: activiti6-boot2   文件: EntityManagerSessionImpl.java
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);
    }
  }
}
 
源代码25 项目: activiti6-boot2   文件: EntityManagerSessionImpl.java
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);
    }
  }
}
 
源代码26 项目: lams   文件: ExtendedEntityManagerCreator.java
/**
 * 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");
			}
		}
	}
}
 
源代码27 项目: lams   文件: SessionImpl.java
@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 ) );

}
 
源代码28 项目: lams   文件: ProcedureCallImpl.java
@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();
	}
}
 
/**
 * 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");
			}
		}
	}
}
 
@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());
}
 
 类所在包
 同包方法