类javax.persistence.RollbackException源码实例Demo

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

private static void endTransaction(EntityTransaction tx) {
    if (tx != null && tx.isActive()) {
        if (tx.getRollbackOnly()) {
            tx.rollback();
        } else {
            try {
                tx.commit();
            } catch (RollbackException e) {
                if (tx.isActive()) {
                    tx.rollback();
                }
                throw e;
            }
        }
    }
}
 
源代码2 项目: mycore   文件: MCRJPATestCase.java
protected void endTransaction() {
    getEntityManager().ifPresent(em -> {
        EntityTransaction tx = em.getTransaction();
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            } else {
                try {
                    tx.commit();
                } catch (RollbackException e) {
                    if (tx.isActive()) {
                        tx.rollback();
                    }
                    throw e;
                }
            }
        }
    });
}
 
源代码3 项目: james-project   文件: JPAMailboxMapper.java
/**
 * Commit the transaction. If the commit fails due a conflict in a unique key constraint a {@link MailboxExistsException}
 * will get thrown
 */
@Override
protected void commit() throws MailboxException {
    try {
        getEntityManager().getTransaction().commit();
    } catch (PersistenceException e) {
        if (e instanceof EntityExistsException) {
            throw new MailboxExistsException(lastMailboxName);
        }
        if (e instanceof RollbackException) {
            Throwable t = e.getCause();
            if (t instanceof EntityExistsException) {
                throw new MailboxExistsException(lastMailboxName);
            }
        }
        throw new MailboxException("Commit of transaction failed", e);
    }
}
 
源代码4 项目: pnc   文件: ProductMilestoneTest.java
@Test
public void shouldNotCreateProductMilestoneWithMalformedVersion() {
    // given
    ProductMilestone productMilestone = ProductMilestone.Builder.newBuilder()
            .version("1.0.0-CD1")
            .productVersion(productVersion)
            .build();

    // when-then
    try {
        em.getTransaction().begin();
        em.persist(productMilestone);
        em.getTransaction().commit();
    } catch (RollbackException ex) {
        if (!(ex.getCause() instanceof ConstraintViolationException))
            fail("Creation of ProductMilestones with malformed version should not be allowed");
    }
}
 
源代码5 项目: pnc   文件: ModelValidationTest.java
@Test
public void testProductVersionStringValidationFailureOnCommit() throws Exception {

    ProductVersion productVersion1 = ProductVersion.Builder.newBuilder()
            .product(Product.Builder.newBuilder().id(1).build())
            .version("foo") // Invalid version string
            .build();

    EntityManager em = getEmFactory().createEntityManager();
    EntityTransaction tx1 = em.getTransaction();

    try {
        tx1.begin();
        em.persist(productVersion1);
        tx1.commit(); // This should throw a Rollback exception caused by the constraint violation

    } catch (RollbackException e) {
        if (tx1 != null && tx1.isActive()) {
            tx1.rollback();
        }
        Assert.assertTrue(e.getCause() instanceof ConstraintViolationException);
    } finally {
        em.close();
    }

}
 
源代码6 项目: elexis-3-core   文件: ConfigTest.java
@Test
public void optimisticLock() throws InterruptedException{
	IConfig config1 = coreModelService.create(IConfig.class);
	config1.setKey("test key 1");
	config1.setValue("test value 1");
	assertTrue(coreModelService.save(config1));
	ExecutorService executor = Executors.newSingleThreadExecutor();
	executor.execute(new Runnable() {
		@Override
		public void run(){
			int affected = coreModelService
				.executeNativeUpdate("UPDATE config SET wert = 'test key', lastupdate = "
					+ 1 + " WHERE param = 'test key 1'", false);
			assertEquals(1, affected);
		}
	});
	executor.awaitTermination(1000, TimeUnit.MILLISECONDS);
	config1.setValue("test key 1");
	RollbackException rbe = null;
	try {
		coreModelService.save(config1);
	} catch (RollbackException e) {
		rbe = e;
	}
	assertNotNull(rbe);
}
 
@Test
public void testTransactionCommitWithRollbackException() {
	given(manager.getTransaction()).willReturn(tx);
	given(tx.getRollbackOnly()).willReturn(true);
	willThrow(new RollbackException()).given(tx).commit();

	final List<String> l = new ArrayList<>();
	l.add("test");

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	try {
		Object result = tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.hasResource(factory));
				EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
				return l;
			}
		});
		assertSame(l, result);
	}
	catch (TransactionSystemException tse) {
		// expected
		assertTrue(tse.getCause() instanceof RollbackException);
	}

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
@Test
public void testTransactionCommitWithRollbackException() {
	given(manager.getTransaction()).willReturn(tx);
	given(tx.getRollbackOnly()).willReturn(true);
	willThrow(new RollbackException()).given(tx).commit();

	final List<String> l = new ArrayList<>();
	l.add("test");

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	try {
		Object result = tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.hasResource(factory));
				EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
				return l;
			}
		});
		assertSame(l, result);
	}
	catch (TransactionSystemException tse) {
		// expected
		assertTrue(tse.getCause() instanceof RollbackException);
	}

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
源代码9 项目: multiapps-controller   文件: PersistenceService.java
public T add(T object) {
    D dto = getPersistenceObjectMapper().toDto(object);
    try {
        D newDto = executeInTransaction(manager -> {
            manager.persist(dto);
            return dto;
        });
        return getPersistenceObjectMapper().fromDto(newDto);
    } catch (RollbackException e) {
        LOGGER.error(MessageFormat.format(Messages.ERROR_WHILE_EXECUTING_TRANSACTION, e.getMessage()));
        onEntityConflict(dto, e);
    }
    return null;
}
 
源代码10 项目: multiapps-controller   文件: PersistenceService.java
public T update(P primaryKey, T newObject) {
    D newDto = getPersistenceObjectMapper().toDto(newObject);
    try {
        return executeInTransaction(manager -> update(primaryKey, newDto, manager));
    } catch (RollbackException e) {
        LOGGER.error(MessageFormat.format(Messages.ERROR_WHILE_EXECUTING_TRANSACTION, e.getMessage()));
        onEntityConflict(newDto, e);
    }
    return null;
}
 
源代码11 项目: lams   文件: ExceptionConverterImpl.java
@Override
public RuntimeException convertCommitException(RuntimeException e) {
	if ( isJpaBootstrap ) {
		Throwable wrappedException;
		if ( e instanceof HibernateException ) {
			wrappedException = convert( (HibernateException) e );
		}
		else if ( e instanceof PersistenceException ) {
			Throwable cause = e.getCause() == null ? e : e.getCause();
			if ( cause instanceof HibernateException ) {
				wrappedException = convert( (HibernateException) cause );
			}
			else {
				wrappedException = cause;
			}
		}
		else {
			wrappedException = e;
		}
		try {
			//as per the spec we should rollback if commit fails
			sharedSessionContract.getTransaction().rollback();
		}
		catch (Exception re) {
			//swallow
		}
		return new RollbackException( "Error while committing the transaction", wrappedException );
	}
	else {
		return e;
	}
}
 
@Test
public void testTransactionCommitWithRollbackException() {
	given(manager.getTransaction()).willReturn(tx);
	given(tx.getRollbackOnly()).willReturn(true);
	willThrow(new RollbackException()).given(tx).commit();

	final List<String> l = new ArrayList<String>();
	l.add("test");

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	try {
		Object result = tt.execute(new TransactionCallback() {
			@Override
			public Object doInTransaction(TransactionStatus status) {
				assertTrue(TransactionSynchronizationManager.hasResource(factory));
				EntityManagerFactoryUtils.getTransactionalEntityManager(factory).flush();
				return l;
			}
		});
		assertSame(l, result);
	}
	catch (TransactionSystemException tse) {
		// expected
		assertTrue(tse.getCause() instanceof RollbackException);
	}

	assertTrue(!TransactionSynchronizationManager.hasResource(factory));
	assertTrue(!TransactionSynchronizationManager.isSynchronizationActive());

	verify(manager).flush();
	verify(manager).close();
}
 
源代码13 项目: ci-spring-boot   文件: TaskRepositoryTest.java
@Test(expected= TransactionSystemException.class)
public void shouldBeFailToUpdateWithoutDescription() {
	try {
		Task task = taskRepository.save(new Task("Test"));
		task.setDescription(null);
		taskRepository.save(task);
	} catch (TransactionSystemException e) {
		((ConstraintViolationException)((RollbackException)e.getCause()).getCause()).getConstraintViolations().forEach(c -> {
			c.getPropertyPath().forEach(f -> Assert.assertEquals("description", f.getName()));
		});
		throw e;
	}
}
 
源代码14 项目: nomulus   文件: JpaTransactionManagerImplTest.java
@Test
public void saveNew_throwsExceptionIfEntityExists() {
  assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isFalse();
  jpaTm().transact(() -> jpaTm().saveNew(theEntity));
  assertThat(jpaTm().transact(() -> jpaTm().checkExists(theEntity))).isTrue();
  assertThat(jpaTm().transact(() -> jpaTm().load(theEntityKey))).isEqualTo(theEntity);
  assertThrows(RollbackException.class, () -> jpaTm().transact(() -> jpaTm().saveNew(theEntity)));
}
 
源代码15 项目: nomulus   文件: JpaTransactionManagerImplTest.java
@Test
public void saveAllNew_rollsBackWhenFailure() {
  moreEntities.forEach(
      entity -> assertThat(jpaTm().transact(() -> jpaTm().checkExists(entity))).isFalse());
  jpaTm().transact(() -> jpaTm().saveNew(moreEntities.get(0)));
  assertThrows(
      RollbackException.class, () -> jpaTm().transact(() -> jpaTm().saveAllNew(moreEntities)));
  assertThat(jpaTm().transact(() -> jpaTm().checkExists(moreEntities.get(0)))).isTrue();
  assertThat(jpaTm().transact(() -> jpaTm().checkExists(moreEntities.get(1)))).isFalse();
  assertThat(jpaTm().transact(() -> jpaTm().checkExists(moreEntities.get(2)))).isFalse();
}
 
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}
 
@Override
public void commit() {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("commit()");
    if (failCommit) {
        throw new RollbackException();
    }
}
 
@Test
public void testExplicitOptimisticLocking() {

    try {
        doInJPA(entityManager -> {
            LOGGER.info("Alice loads the Post entity");
            Post post = entityManager.find(Post.class, 1L);

            executeSync(() -> {
                doInJPA(_entityManager -> {
                    LOGGER.info("Bob loads the Post entity and modifies it");
                    Post _post = _entityManager.find(Post.class, 1L);
                    _post.setBody("Chapter 17 summary");
                });
            });

            entityManager.lock(post, LockModeType.OPTIMISTIC);

            LOGGER.info("Alice adds a PostComment to the previous Post entity version");
            PostComment comment = new PostComment();
            comment.setId(1L);
            comment.setReview("Chapter 16 is about Caching.");
            comment.setPost(post);
            entityManager.persist(comment);
        });
        fail("It should have thrown OptimisticEntityLockException!");
    } catch (RollbackException expected) {
        assertEquals(OptimisticLockException.class, expected.getCause().getClass());
        LOGGER.info("Failure: ", expected);
    }
}
 
源代码19 项目: pnc   文件: BuildConfigurationTest.java
@Test(expected = RollbackException.class)
public void testFailToCreateBCWithoutRepoConfig() {
    BuildConfiguration bc = BuildConfiguration.Builder.newBuilder()
            .id(buildConfigurationSequence.incrementAndGet())
            .name("Test Build Configuration 1")
            .project(PROJECT_WITH_ID_1)
            .buildScript("mvn install")
            .buildEnvironment(BUILD_ENVIRONMENT_WITH_ID_1)
            .build();

    em.getTransaction().begin();
    em.persist(bc);
    em.getTransaction().commit();
}
 
源代码20 项目: mycore   文件: MCRStalledJobResetter.java
/**
 * Resets jobs to {@link MCRJobStatus#NEW} that where in status {@link MCRJobStatus#PROCESSING} for to long time.
 */
public void run() {
    EntityManager em = MCREntityManagerProvider.getEntityManagerFactory().createEntityManager();
    EntityTransaction transaction = em.getTransaction();

    LOGGER.info("MCRJob is Checked for dead Entries");
    transaction.begin();

    StringBuilder sb = new StringBuilder("FROM MCRJob WHERE ");
    if (action != null) {
        sb.append("action='").append(action.getName()).append("' AND ");
    }
    sb.append(" status='" + MCRJobStatus.PROCESSING + "' ORDER BY id ASC");

    TypedQuery<MCRJob> query = em.createQuery(sb.toString(), MCRJob.class);

    long current = new Date(System.currentTimeMillis()).getTime() / 60000;

    boolean reset = query
        .getResultList()
        .stream()
        .map(job -> {
            boolean ret = false;
            long start = job.getStart().getTime() / 60000;
            if (current - start >= maxTimeDiff) {
                LOGGER.debug("->Resetting too long in queue");

                job.setStatus(MCRJobStatus.NEW);
                job.setStart(null);
                ret = true;
            } else {
                LOGGER.debug("->ok");
            }
            return ret;
        })
        .reduce(Boolean::logicalOr)
        .orElse(false);
    try {
        transaction.commit();
    } catch (RollbackException e) {
        e.printStackTrace();
        if (transaction != null) {
            transaction.rollback();
            reset = false;//No changes are applied, so no notification is needed as well
        }
    }
    //Only notify Listeners on Queue if really something is set back
    if (reset) {
        synchronized (MCRJobQueue.getInstance(action)) {
            MCRJobQueue.getInstance(action).notifyListener();
        }
    }
    em.close();
    LOGGER.info("MCRJob checking is done");
}
 
public void rollback() throws RollbackException {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("rollback()");
}
 
源代码22 项目: development   文件: DeployedSessionBeanTest.java
public void rollback() throws RollbackException {
    fail();
}
 
@Override
public void rollback() throws RollbackException {
    status = Status.STATUS_NO_TRANSACTION;
    stubCalls.add("rollback()");
}
 
源代码24 项目: development   文件: DeployedSessionBeanTest.java
public void rollback() throws RollbackException {
    fail();
}
 
@Test
public void testSameJTATransactionMultipleConnectionsMultipleSessions() {
    SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

    try(Session session1 = sessionFactory.openSession()) {
        session1.beginTransaction();

        session1.persist(new FlexyPoolEntities.Post());

        assertEquals(
            1,
            (session1.createQuery(
                "select count(p) from Post p", Number.class
            ).getSingleResult()).intValue()
        );

        try(Session session2 = extraEntityManagerFactory.unwrap(SessionFactory.class).openSession()) {
            session2.joinTransaction();

            session2.persist(new FlexyPoolEntities.Post());

            assertEquals(
                1,
                (session2.createQuery(
                    "select count(p) from Post p", Number.class
                ).getSingleResult()).intValue()
            );

            session2.getTransaction().rollback();
        }

        session1.getTransaction().commit();
    } catch (Exception e) {
        assertTrue(e instanceof RollbackException);
    }

    try(Session session = sessionFactory.openSession()) {
        assertEquals(
            0,
            (session.createQuery(
                "select count(p) from Post p", Number.class
            ).getSingleResult()).intValue()
        );
    }
}
 
源代码26 项目: syncope   文件: RestServiceExceptionMapper.java
private static ResponseBuilder processInvalidEntityExceptions(final Exception ex) {
    InvalidEntityException iee = null;

    if (ex instanceof InvalidEntityException) {
        iee = (InvalidEntityException) ex;
    }
    if (ex instanceof TransactionSystemException && ex.getCause() instanceof RollbackException
            && ex.getCause().getCause() instanceof InvalidEntityException) {

        iee = (InvalidEntityException) ex.getCause().getCause();
    }

    if (iee != null) {
        ClientExceptionType exType;
        if (iee.getEntityClassSimpleName().endsWith("Policy")) {
            exType = ClientExceptionType.InvalidPolicy;
        } else if (iee.getEntityClassSimpleName().equals(PlainAttr.class.getSimpleName())) {
            exType = ClientExceptionType.InvalidValues;
        } else {
            try {
                exType = ClientExceptionType.valueOf("Invalid" + iee.getEntityClassSimpleName());
            } catch (IllegalArgumentException e) {
                // ignore
                exType = ClientExceptionType.InvalidEntity;
            }
        }

        ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
        builder.header(RESTHeaders.ERROR_CODE, exType.name());

        ErrorTO error = new ErrorTO();
        error.setStatus(exType.getResponseStatus().getStatusCode());
        error.setType(exType);

        for (Map.Entry<Class<?>, Set<EntityViolationType>> violation : iee.getViolations().entrySet()) {
            for (EntityViolationType violationType : violation.getValue()) {
                builder.header(RESTHeaders.ERROR_INFO,
                        exType.getInfoHeaderValue(violationType.name() + ": " + violationType.getMessage()));
                error.getElements().add(violationType.name() + ": " + violationType.getMessage());
            }
        }

        return builder;
    }

    return null;
}
 
 类所在包
 类方法
 同包方法