下面列出了怎么用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();
}
@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 )
);
}
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();
}
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
}
}
@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();
}
}
@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);
}
}
@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);
}
}
@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);
}
}
@Override
public void flush() {
checkBlocking();
try (EntityManagerResult emr = getEntityManager()) {
if (!emr.allowModification) {
throw new TransactionRequiredException(TRANSACTION_IS_NOT_ACTIVE);
}
emr.em.flush();
}
}
@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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
@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);
}
}
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);
}
}
}
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);
}
}
}
/**
* 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");
}
}
}
}
@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 ) );
}
@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());
}