java类javax.persistence.TransactionRequiredException的实例源码

ApplicationManagedEntityManagerIntegrationTests.java 文件源码 项目:spring4-understanding 阅读 29 收藏 0 点赞 0 评论 0
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();
}
Controllable.java 文件源码 项目:cibet 阅读 28 收藏 0 点赞 0 评论 0
/**
 * releases an event on a JPA resource. If it is the second release of a 6-eyes process the controlled object entry
 * is updated. If it is a 4-eyes process the real object is updated.
 * 
 * @param entityManager
 *           EntityManager for performing the release. Could be null in case of a INVOKE event. If JDBC, use new
 *           JdbcBridgeEntityManager(connection)
 * @param remark
 *           comment
 * @throws ResourceApplyException
 *            if the release action fails.
 */
@CibetContext
public Object release(EntityManager entityManager, String remark) throws ResourceApplyException {
   log.debug("start release");

   if (entityManager != null) {
      if ((entityManager instanceof CEntityManager && ((CEntityManager) entityManager).supportsTransactions()
            || !(entityManager instanceof CEntityManager)) && !entityManager.isJoinedToTransaction()) {
         String err = "release method must be called within a transaction boundary";
         log.error(err);
         throw new TransactionRequiredException(err);
      }
      Context.internalRequestScope().setApplicationEntityManager(entityManager);
   }
   if (getExecutionStatus() != ExecutionStatus.SCHEDULED) {
      Context.internalRequestScope().setScheduledDate(getScheduledDate());
   }
   DcActuator dc = (DcActuator) Configuration.instance().getActuator(getActuator());
   Object obj = dc.release(this, remark);
   return obj;
}
ActuatorIT.java 文件源码 项目:cibet 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void releasepersistNoTransaction() throws Exception {
   log.info("start releasepersistNoTransaction()");

   List<String> schemes = new ArrayList<String>();
   schemes.add(FourEyesActuator.DEFAULTNAME);
   registerSetpoint(TEntity.class.getName(), schemes, ControlEvent.INSERT, ControlEvent.RELEASE);
   Context.requestScope().setRemark("created");

   TEntity ent = createTEntity(12, "Hirsch");
   persist(ent);
   Assert.assertEquals(0, ent.getId());

   List<Controllable> l = DcLoader.findUnreleased();
   Assert.assertEquals(1, l.size());
   Controllable co = l.get(0);
   Assert.assertEquals("created", co.getCreateRemark());

   Context.sessionScope().setUser("tester2");
   try {
      co.release(applEman, "blabla");
      Assert.fail();
   } catch (TransactionRequiredException e) {
   }
}
DcManagerImplIntegrationTest.java 文件源码 项目:cibet 阅读 29 收藏 0 点赞 0 评论 0
@Test
public void releasePersistNoTransaction() throws Exception {
   log.info("start releasePersistNoTransaction()");

   registerSetpoint(TEntity.class, FourEyesActuator.DEFAULTNAME, ControlEvent.INSERT, ControlEvent.RELEASE);
   Context.requestScope().setRemark("created");

   TEntity ent = persistTEntity();
   Assert.assertEquals(0, ent.getId());

   List<Controllable> l = DcLoader.findUnreleased();
   Assert.assertEquals(1, l.size());
   Controllable co = l.get(0);
   Assert.assertEquals("created", co.getCreateRemark());
   Context.sessionScope().setUser("test2");

   applEman.getTransaction().commit();

   try {
      co.release(applEman, null);
      Assert.fail();
   } catch (TransactionRequiredException e) {
   }

   applEman.getTransaction().begin();
}
ApplicationManagedEntityManagerIntegrationTests.java 文件源码 项目:class-guard 阅读 23 收藏 0 点赞 0 评论 0
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();
}
JtaEntityManagerRegistry.java 文件源码 项目:tomee 阅读 33 收藏 0 点赞 0 评论 0
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);
    }
}
ExtendedEntityManagerCreator.java 文件源码 项目:lams 阅读 37 收藏 0 点赞 0 评论 0
/**
 * 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");
            }
        }
    }
}
ExtendedEntityManagerCreator.java 文件源码 项目:spring4-understanding 阅读 42 收藏 0 点赞 0 评论 0
/**
 * 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");
            }
        }
    }
}
EntityManagerFactoryUtilsTests.java 文件源码 项目:spring4-understanding 阅读 26 收藏 0 点赞 0 评论 0
@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());
}
ContainerManagedEntityManagerIntegrationTests.java 文件源码 项目:spring4-understanding 阅读 28 收藏 0 点赞 0 评论 0
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testContainerEntityManagerProxyRejectsJoinTransactionWithoutTransaction() {
    try {
        createContainerManagedEntityManager().joinTransaction();
        fail("Should have thrown a TransactionRequiredException");
    }
    catch (TransactionRequiredException e) {
        /* expected */
    }
}
RequestScopeContext.java 文件源码 项目:cibet 阅读 31 收藏 0 点赞 0 评论 0
/**
 * Return the EntityManager instance for persistence of the Cibet entities.
 * 
 * @return
 * @throws CibetException
 *            if no EntityManager set in CibetContext
 */
@Override
public EntityManager getOrCreateEntityManager(boolean transacted) {
   EntityManager manager = (EntityManager) getProperty(CIBET_ENTITYMANAGER);
   if (manager == null) {
      manager = Context.getOrCreateEntityManagers();
      if (manager == null) {
         throw new CibetException("No Cibet EntityManager set in CibetContext");
      }
   }
   if (log.isDebugEnabled()) {
      log.debug("get Cibet EntityManager from CibetContext: " + manager);
   }

   EntityManagerType emType = (EntityManagerType) getProperty(ENTITYMANAGER_TYPE);
   if (EntityManagerType.JTA == emType) {
      try {
         manager.joinTransaction();
         log.debug("... and join JTA transaction");
      } catch (TransactionRequiredException e) {
         log.info("... but cannot join transaction: " + e.getMessage());
      }
   }

   if (transacted && manager instanceof CEntityManager && ((CEntityManager) manager).supportsTransactions()
         && !manager.isJoinedToTransaction()) {
      throw new TransactionRequiredException();
   }
   return manager;
}
EntityManagerSessionImpl.java 文件源码 项目:flowable-engine 阅读 37 收藏 0 点赞 0 评论 0
@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);
        }
    }
}
EntityManagerSessionImpl.java 文件源码 项目:flowable-engine 阅读 24 收藏 0 点赞 0 评论 0
@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);
        }
    }
}
UsersController.java 文件源码 项目:hopsworks 阅读 30 收藏 0 点赞 0 评论 0
public void updateStatus(Users id, PeopleAccountStatus stat) throws ApplicationException {
  id.setStatus(stat);
  try {
    userFacade.update(id);
  } catch (TransactionRequiredException ex) {
    throw new ApplicationException("Need a transaction to update the user status");
  }
}
EntityManagerSessionImpl.java 文件源码 项目:SecureBPMN 阅读 28 收藏 0 点赞 0 评论 0
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);
    }
  }
}
EntityProxyInvocationHandler.java 文件源码 项目:osgi.ee 阅读 34 收藏 0 点赞 0 评论 0
/**
 * Register an entity manager with a transaction manager.
 *
 * @param manager The entity manager to register, which is a non-proxy one
 * @param local The thread local that maintains the entity managers for the various threads
 * @param transactionManager The transaction manager to register with
 */
private static void registerEntityManagerUnknown(EntityManager manager, final ThreadLocal<EntityManager> local,
        final TransactionManager transactionManager) throws Exception {
    try {
        manager.joinTransaction();
        Synchronization sync = new JTASynchronization(manager, local);
        transactionManager.getTransaction().registerSynchronization(sync);
    } catch (TransactionRequiredException exc) {
        registerEntityManagerResourceLocal(manager, local, transactionManager);
    }
}
ExtendedEntityManagerCreator.java 文件源码 项目:class-guard 阅读 37 收藏 0 点赞 0 评论 0
/**
 * 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");
            }
        }
    }
}
EntityManagerFactoryUtilsTests.java 文件源码 项目:class-guard 阅读 26 收藏 0 点赞 0 评论 0
@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());
}
EntityManagerSessionImpl.java 文件源码 项目:FiWare-Template-Handler 阅读 23 收藏 0 点赞 0 评论 0
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);
    }
  }
}
TrackerSerializer.java 文件源码 项目:exportlibrary 阅读 34 收藏 0 点赞 0 评论 0
public Long serializeProcedureSubmissionSet(long trackerID, Calendar submissionDate, String submissionFilename) throws JAXBException, FileNotFoundException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, XMLloadingException, IOException {
    this.submissionset = new SubmissionSet();
    this.submission = new Submission();
    this.submissionset.getSubmission().add(this.submission);
    this.submission.setTrackerID(trackerID);
    this.submission.setSubmissionDate(submissionDate);
    this.loadProcedureResults(submissionFilename);
    return this.serializeSubmissionSet();
}
TrackerSerializer.java 文件源码 项目:exportlibrary 阅读 32 收藏 0 点赞 0 评论 0
public Long serializeSpecimenSubmissionSet(long trackerID, Calendar submissionDate, String submissionFilename) throws JAXBException, FileNotFoundException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, XMLloadingException, IOException {
    this.submissionset = new SubmissionSet();
    this.submission = new Submission();
    this.submissionset.getSubmission().add(this.submission);
    this.submission.setTrackerID(trackerID);
    this.submission.setSubmissionDate(submissionDate);
    this.loadSpecimens(submissionFilename);
    return this.serializeSubmissionSet();
}
Serializer.java 文件源码 项目:exportlibrary 阅读 31 收藏 0 点赞 0 评论 0
public void serialize(T object, Class<T> clazz) throws JAXBException, IllegalStateException, EntityExistsException, IllegalArgumentException, TransactionRequiredException, RuntimeException, Exception {
    if (toXml) {
        if (Connector.validType(clazz)) {
            this.marshall(object);
        } else {
            logger.error("class {} cannot be serializeda as a xml document");
            throw new Exception("class " + clazz.getName() + "cannot be serializeda as a xml document");
        }
    } else {
        this.persist(object);
    }
}
UserServiceImplControllerTest.java 文件源码 项目:fuwesta 阅读 25 收藏 0 点赞 0 评论 0
/**
 * Reset entity-Manager this should fail (no-transaction), but to be sure.
 */
private void resetEntityManager() {
    try {
        em.clear();
    } catch (TransactionRequiredException e) {
        // expected.
    }
}
EntityManagerSessionImpl.java 文件源码 项目:xbpm5 阅读 26 收藏 0 点赞 0 评论 0
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);
    }
  }
}
EntityManagerSessionImpl.java 文件源码 项目:camunda-bpm-platform 阅读 25 收藏 0 点赞 0 评论 0
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);
    }
  }
}
EntityManagerFactoryUtils.java 文件源码 项目:lams 阅读 33 收藏 0 点赞 0 评论 0
/**
 * Convert the given runtime exception to an appropriate exception from the
 * {@code org.springframework.dao} hierarchy.
 * Return null if no translation is appropriate: any other exception may
 * have resulted from user code, and should not be translated.
 * <p>The most important cases like object not found or optimistic locking failure
 * are covered here. For more fine-granular conversion, JpaTransactionManager etc
 * support sophisticated translation of exceptions via a JpaDialect.
 * @param ex runtime exception that occurred
 * @return the corresponding DataAccessException instance,
 * or {@code null} if the exception should not be translated
 */
public static DataAccessException convertJpaAccessExceptionIfPossible(RuntimeException ex) {
    // Following the JPA specification, a persistence provider can also
    // throw these two exceptions, besides PersistenceException.
    if (ex instanceof IllegalStateException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof IllegalArgumentException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }

    // Check for well-known PersistenceException subclasses.
    if (ex instanceof EntityNotFoundException) {
        return new JpaObjectRetrievalFailureException((EntityNotFoundException) ex);
    }
    if (ex instanceof NoResultException) {
        return new EmptyResultDataAccessException(ex.getMessage(), 1, ex);
    }
    if (ex instanceof NonUniqueResultException) {
        return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex);
    }
    if (ex instanceof QueryTimeoutException) {
        return new org.springframework.dao.QueryTimeoutException(ex.getMessage(), ex);
    }
    if (ex instanceof LockTimeoutException) {
        return new CannotAcquireLockException(ex.getMessage(), ex);
    }
    if (ex instanceof PessimisticLockException) {
        return new PessimisticLockingFailureException(ex.getMessage(), ex);
    }
    if (ex instanceof OptimisticLockException) {
        return new JpaOptimisticLockingFailureException((OptimisticLockException) ex);
    }
    if (ex instanceof EntityExistsException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }
    if (ex instanceof TransactionRequiredException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }

    // If we have another kind of PersistenceException, throw it.
    if (ex instanceof PersistenceException) {
        return new JpaSystemException((PersistenceException) ex);
    }

    // If we get here, we have an exception that resulted from user code,
    // rather than the persistence provider, so we return null to indicate
    // that translation should not occur.
    return null;
}
EntityManagerFactoryUtils.java 文件源码 项目:spring4-understanding 阅读 36 收藏 0 点赞 0 评论 0
/**
 * Convert the given runtime exception to an appropriate exception from the
 * {@code org.springframework.dao} hierarchy.
 * Return null if no translation is appropriate: any other exception may
 * have resulted from user code, and should not be translated.
 * <p>The most important cases like object not found or optimistic locking failure
 * are covered here. For more fine-granular conversion, JpaTransactionManager etc
 * support sophisticated translation of exceptions via a JpaDialect.
 * @param ex runtime exception that occurred
 * @return the corresponding DataAccessException instance,
 * or {@code null} if the exception should not be translated
 */
public static DataAccessException convertJpaAccessExceptionIfPossible(RuntimeException ex) {
    // Following the JPA specification, a persistence provider can also
    // throw these two exceptions, besides PersistenceException.
    if (ex instanceof IllegalStateException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }
    if (ex instanceof IllegalArgumentException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }

    // Check for well-known PersistenceException subclasses.
    if (ex instanceof EntityNotFoundException) {
        return new JpaObjectRetrievalFailureException((EntityNotFoundException) ex);
    }
    if (ex instanceof NoResultException) {
        return new EmptyResultDataAccessException(ex.getMessage(), 1, ex);
    }
    if (ex instanceof NonUniqueResultException) {
        return new IncorrectResultSizeDataAccessException(ex.getMessage(), 1, ex);
    }
    if (ex instanceof QueryTimeoutException) {
        return new org.springframework.dao.QueryTimeoutException(ex.getMessage(), ex);
    }
    if (ex instanceof LockTimeoutException) {
        return new CannotAcquireLockException(ex.getMessage(), ex);
    }
    if (ex instanceof PessimisticLockException) {
        return new PessimisticLockingFailureException(ex.getMessage(), ex);
    }
    if (ex instanceof OptimisticLockException) {
        return new JpaOptimisticLockingFailureException((OptimisticLockException) ex);
    }
    if (ex instanceof EntityExistsException) {
        return new DataIntegrityViolationException(ex.getMessage(), ex);
    }
    if (ex instanceof TransactionRequiredException) {
        return new InvalidDataAccessApiUsageException(ex.getMessage(), ex);
    }

    // If we have another kind of PersistenceException, throw it.
    if (ex instanceof PersistenceException) {
        return new JpaSystemException((PersistenceException) ex);
    }

    // If we get here, we have an exception that resulted from user code,
    // rather than the persistence provider, so we return null to indicate
    // that translation should not occur.
    return null;
}
SharedEntityManagerCreatorTests.java 文件源码 项目:spring4-understanding 阅读 28 收藏 0 点赞 0 评论 0
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnJoinTransaction() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    em.joinTransaction();
}
SharedEntityManagerCreatorTests.java 文件源码 项目:spring4-understanding 阅读 22 收藏 0 点赞 0 评论 0
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnFlush() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    em.flush();
}
SharedEntityManagerCreatorTests.java 文件源码 项目:spring4-understanding 阅读 27 收藏 0 点赞 0 评论 0
@Test(expected = TransactionRequiredException.class)
public void transactionRequiredExceptionOnPersist() {
    EntityManagerFactory emf = mock(EntityManagerFactory.class);
    EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf);
    em.persist(new Object());
}


问题


面经


文章

微信
公众号

扫码关注公众号