javax.persistence.RollbackException Java Examples
The following examples show how to use
javax.persistence.RollbackException.
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: ConfigTest.java From elexis-3-core with Eclipse Public License 1.0 | 6 votes |
@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); }
Example #2
Source File: ModelValidationTest.java From pnc with Apache License 2.0 | 6 votes |
@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(); } }
Example #3
Source File: ProductMilestoneTest.java From pnc with Apache License 2.0 | 6 votes |
@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"); } }
Example #4
Source File: MCRURNGranularRESTRegistrationTask.java From mycore with GNU General Public License v3.0 | 6 votes |
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; } } } }
Example #5
Source File: JPAMailboxMapper.java From james-project with Apache License 2.0 | 6 votes |
/** * 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); } }
Example #6
Source File: MCRJPATestCase.java From mycore with GNU General Public License v3.0 | 6 votes |
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; } } } }); }
Example #7
Source File: JpaTransactionManagerTests.java From java-technology-stack with MIT License | 5 votes |
@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(); }
Example #8
Source File: BuildConfigurationTest.java From pnc with Apache License 2.0 | 5 votes |
@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(); }
Example #9
Source File: LockModeOptimisticTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
@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); } }
Example #10
Source File: TransactionInvocationHandlersTest.java From development with Apache License 2.0 | 5 votes |
@Override public void commit() { status = Status.STATUS_NO_TRANSACTION; stubCalls.add("commit()"); if (failCommit) { throw new RollbackException(); } }
Example #11
Source File: TransactionInvocationHandlersTest.java From development with Apache License 2.0 | 5 votes |
public void commit() { status = Status.STATUS_NO_TRANSACTION; stubCalls.add("commit()"); if (failCommit) { throw new RollbackException(); } }
Example #12
Source File: JpaTransactionManagerImplTest.java From nomulus with Apache License 2.0 | 5 votes |
@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(); }
Example #13
Source File: JpaTransactionManagerImplTest.java From nomulus with Apache License 2.0 | 5 votes |
@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))); }
Example #14
Source File: TaskRepositoryTest.java From ci-spring-boot with MIT License | 5 votes |
@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; } }
Example #15
Source File: JpaTransactionManagerTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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(); }
Example #16
Source File: ExceptionConverterImpl.java From lams with GNU General Public License v2.0 | 5 votes |
@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; } }
Example #17
Source File: PersistenceService.java From multiapps-controller with Apache License 2.0 | 5 votes |
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; }
Example #18
Source File: PersistenceService.java From multiapps-controller with Apache License 2.0 | 5 votes |
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; }
Example #19
Source File: JpaTransactionManagerTests.java From spring-analysis-note with MIT License | 5 votes |
@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(); }
Example #20
Source File: TransactionInvocationHandlersTest.java From development with Apache License 2.0 | 4 votes |
public void rollback() throws RollbackException { status = Status.STATUS_NO_TRANSACTION; stubCalls.add("rollback()"); }
Example #21
Source File: DeployedSessionBeanTest.java From development with Apache License 2.0 | 4 votes |
public void rollback() throws RollbackException { fail(); }
Example #22
Source File: TransactionInvocationHandlersTest.java From development with Apache License 2.0 | 4 votes |
@Override public void rollback() throws RollbackException { status = Status.STATUS_NO_TRANSACTION; stubCalls.add("rollback()"); }
Example #23
Source File: DeployedSessionBeanTest.java From development with Apache License 2.0 | 4 votes |
public void rollback() throws RollbackException { fail(); }
Example #24
Source File: JTAMultipleTransactionsTest.java From high-performance-java-persistence with Apache License 2.0 | 4 votes |
@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() ); } }
Example #25
Source File: MCRStalledJobResetter.java From mycore with GNU General Public License v3.0 | 4 votes |
/** * 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"); }
Example #26
Source File: RestServiceExceptionMapper.java From syncope with Apache License 2.0 | 4 votes |
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; }