Java Code Examples for javax.persistence.EntityTransaction#rollback()

The following examples show how to use javax.persistence.EntityTransaction#rollback() . 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: CustomerDB.java    From MusicStore with MIT License 6 votes vote down vote up
/**
 * @param customer The customer to be updated
 */
public static void update(Customer customer) {
   EntityManager em = DBUtil.getEmFactory().createEntityManager();
   EntityTransaction transaction = em.getTransaction();

   try {
      transaction.begin();
      em.merge(customer);
      transaction.commit();
   } catch (Exception e) {
      System.out.println(e);
      transaction.rollback();
   } finally {
      em.close();
   }
}
 
Example 2
Source File: JPASubscriptionMapper.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Override
public void delete(Subscription subscription) throws SubscriptionException {
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    boolean localTransaction = !transaction.isActive();
    if (localTransaction) {
        transaction.begin();
    }
    try {
        findJpaSubscription(entityManager, subscription)
            .ifPresent(entityManager::remove);
        if (localTransaction) {
            if (transaction.isActive()) {
                transaction.commit();
            }
        }
    } catch (PersistenceException e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new SubscriptionException(e);
    }
}
 
Example 3
Source File: TransactionRunner.java    From james-project with Apache License 2.0 6 votes vote down vote up
public <T> T runAndRetrieveResult(Function<EntityManager, T> toResult,
                                  Function<PersistenceException, T> errorHandler) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        T result = toResult.apply(entityManager);
        transaction.commit();
        return result;
    } catch (PersistenceException e) {
        LOGGER.warn("Could not execute transaction", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        return errorHandler.apply(e);
    } finally {
        EntityManagerUtils.safelyClose(entityManager);
    }
}
 
Example 4
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 6 votes vote down vote up
@OperationLogPointcut(operation = Modification, objectClass = CiData.class)
@Override
public List<Map<String, Object>>  refresh(@Guid List<CiIndentity> ciIds) {
    List<Map<String, Object>> results = Lists.newLinkedList();
    PriorityEntityManager priEntityManager = getEntityManager();
    EntityManager entityManager = priEntityManager.getEntityManager();

    EntityTransaction transaction = entityManager.getTransaction();
    transaction.begin();
    try {
        for (CiIndentity ciId : ciIds) {

            DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciId.getCiTypeId());
            Object entityBean = validateCi(ciId.getCiTypeId(), ciId.getGuid(), entityMeta, entityManager, null);
            DynamicEntityHolder entityHolder = new DynamicEntityHolder(entityMeta, entityBean);

            ciDataInterceptorService.refreshAutoFill(entityHolder,entityManager,entityHolder.getEntityBeanMap());
            results.add(ImmutableMap.of("guid",ciId.getGuid()));
        }
        transaction.commit();
    }finally {
        transaction.rollback();
        priEntityManager.close();
    }
    return results;
}
 
Example 5
Source File: JpaTransactionManager.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected void doRollback(DefaultTransactionStatus status) {
	JpaTransactionObject txObject = (JpaTransactionObject) status.getTransaction();
	if (status.isDebug()) {
		logger.debug("Rolling back JPA transaction on EntityManager [" +
				txObject.getEntityManagerHolder().getEntityManager() + "]");
	}
	try {
		EntityTransaction tx = txObject.getEntityManagerHolder().getEntityManager().getTransaction();
		if (tx.isActive()) {
			tx.rollback();
		}
	}
	catch (PersistenceException ex) {
		throw new TransactionSystemException("Could not roll back JPA transaction", ex);
	}
	finally {
		if (!txObject.isNewEntityManagerHolder()) {
			// Clear all pending inserts/updates/deletes in the EntityManager.
			// Necessary for pre-bound EntityManagers, to avoid inconsistent state.
			txObject.getEntityManagerHolder().getEntityManager().clear();
		}
	}
}
 
Example 6
Source File: InfinispanHibernateCacheSpringLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private void updateEntity(long id) {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         Event event = em.find(Event.class, id);
         event.setName("Caught a Snorlax!!");

         log.info(String.format("Updated entity: %s", event));
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
Example 7
Source File: EntityTestBase.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
 
Example 8
Source File: JpaTest.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        // 1、获取EntityManager
        em = JpaUtil.getEntityManager();
        // 2、获取事务
        tx = em.getTransaction();
        // 3、开启事务
        tx.begin();
        // 4、获取数据、删除数据
        // primaryKey类型必须和实体主键类型一致,否则查询不到
        Customer customer = em.find(Customer.class, 2L);
        System.out.println(customer);
        // 5、提交事务
        tx.commit();
    } catch (Exception e) {
        if (tx != null) tx.rollback();
    } finally {
        if (em != null) em.close();
    }
}
 
Example 9
Source File: EntityTestBase.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected boolean persistInATransaction(Object... obj) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();

    try {
        for(Object o : obj) {
            em.persist(o);
        }
        tx.commit();
    } catch (Exception e) {
        System.out.println("FAILED TRANSACTION: " + e.toString());
        tx.rollback();
        return false;
    }

    return true;
}
 
Example 10
Source File: LdapExpandedAuthenticator.java    From juddi with Apache License 2.0 6 votes vote down vote up
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException, FatalErrorException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        Publisher publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));
        return publisher;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}
 
Example 11
Source File: InfinispanHibernateCacheSpringLocal.java    From infinispan-simple-tutorials with Apache License 2.0 6 votes vote down vote up
private void saveExpiringEntity() {
   try (Session em = createEntityManagerWithStatsCleared()) {
      EntityTransaction tx = em.getTransaction();
      try {
         tx.begin();

         em.persist(new Person("Satoshi"));
      } catch (Throwable t) {
         tx.setRollbackOnly();
         throw t;
      } finally {
         if (tx.isActive()) tx.commit();
         else tx.rollback();
      }
   }
}
 
Example 12
Source File: DownloadDB.java    From MusicStore with MIT License 6 votes vote down vote up
/**
 * Inserts a Download object into the database
 *
 * @param download The download to be inserted
 */
public static void insert(Download download) {
   EntityManager em = DBUtil.getEmFactory().createEntityManager();
   EntityTransaction transaction = em.getTransaction();

   try {
      transaction.begin();
      em.persist(download);
      transaction.commit();
   } catch (Exception e) {
      System.err.println(e);
      transaction.rollback();
   } finally {
      em.close();
   }
}
 
Example 13
Source File: JPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void verifyHqlFetch(EntityManagerFactory emf) {
    EntityManager em = emf.createEntityManager();
    try {
        EntityTransaction transaction = em.getTransaction();
        try {
            transaction.begin();

            em.createQuery("from Person p left join fetch p.address a").getResultList();

            transaction.commit();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }
    } finally {
        em.close();
    }
}
 
Example 14
Source File: AbstractJavaEEIntegrationTest.java    From flexy-pool with Apache License 2.0 5 votes vote down vote up
private void doInTransaction(VoidCallable callable) {
    EntityTransaction entityTransaction = null;
    try {
        entityTransaction = entityManager.getTransaction();
        entityTransaction.begin();
        callable.call();
        entityTransaction.commit();
    } catch (Exception e) {
        if (entityTransaction != null && entityTransaction.isActive()) {
            entityTransaction.rollback();
        }
        throw new IllegalStateException(e);
    }
}
 
Example 15
Source File: AbstractModelTest.java    From pnc with Apache License 2.0 5 votes vote down vote up
/**
 * Delete data from all database tables
 */
protected static void clearDatabaseTables() {

    EntityManager em = getEmFactory().createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.createNativeQuery("SET DATABASE REFERENTIAL INTEGRITY FALSE").executeUpdate();
        em.createNativeQuery("delete from Artifact").executeUpdate();
        em.createNativeQuery("delete from BuildConfiguration").executeUpdate();
        em.createNativeQuery("delete from BuildConfiguration_aud").executeUpdate();
        em.createNativeQuery("delete from RepositoryConfiguration").executeUpdate();
        em.createNativeQuery("delete from BuildEnvironment").executeUpdate();
        em.createNativeQuery("delete from BuildRecord").executeUpdate();
        em.createNativeQuery("delete from Product").executeUpdate();
        em.createNativeQuery("delete from ProductMilestone").executeUpdate();
        em.createNativeQuery("delete from ProductRelease").executeUpdate();
        em.createNativeQuery("delete from ProductVersion").executeUpdate();
        em.createNativeQuery("delete from Project").executeUpdate();
        em.createNativeQuery("delete from UserTable").executeUpdate();
        em.createNativeQuery("delete from TargetRepository").executeUpdate();
        em.createNativeQuery("SET DATABASE REFERENTIAL INTEGRITY TRUE").executeUpdate();
        tx.commit();

    } catch (RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw e;
    } finally {
        em.close();
    }
}
 
Example 16
Source File: UserTest.java    From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testPersistAndModify() {

    String before = "before";
    String during = "during";
    String after = "after";

    User user = new User();
    user.setName(before);

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        em.persist(user);
        /*
            the transaction is not finished, so, any modification to the attached
            object will be committed to the DB
         */
        user.setName(during);
        tx.commit();
    } catch (Exception e) {
        tx.rollback();
        fail();
    }

    //this is done after the transaction, so no effect on DB
    user.setName(after);

    //make sure we clear the cache, making all entity objects detached
    em.clear();

    //read operations like this do not need an explicit transaction
    User found = em.find(User.class, user.getId());

    assertEquals(during, found.getName());
    assertEquals(after, user.getName());
}
 
Example 17
Source File: BaseDao.java    From ranger with Apache License 2.0 5 votes vote down vote up
public void rollbackTransaction() {
	EntityManager em = getEntityManager();

	if(em != null) {
		EntityTransaction et = em.getTransaction();

		if(et != null) {
			et.rollback();
		}
	}
}
 
Example 18
Source File: EntityTransactionManager.java    From enkan with Eclipse Public License 1.0 5 votes vote down vote up
public void required(Runnable r) {
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        r.run();
        tx.commit();
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        throw e;
    }
}
 
Example 19
Source File: AbstractPlainJpa.java    From vaadinator with Apache License 2.0 5 votes vote down vote up
protected Object requireJpaTransaction(Callback callback, Map<String, Object> context) {
	EntityTransaction transaction = null;
	EntityManager entityManager = null;
	boolean newTransaction = entityManagers.get() == null;
	if (newTransaction) {
		entityManager = entityManagerFactory.createEntityManager();
		transaction = entityManager.getTransaction();
		transaction.begin();
		entityManagers.set(entityManager);
	}
	boolean success = false;
	try {
		Object res = callback.perform();
		if (newTransaction) {
			transaction.commit();
		}
		success = true;
		return res;
	} finally {
		if (newTransaction) {
			entityManagers.remove();
			try {
				if ((!success) && transaction.isActive()) {
					transaction.rollback();
				}
			} finally {
				entityManager.close();
			}
		}
	}
}
 
Example 20
Source File: ValidatePublish.java    From juddi with Apache License 2.0 4 votes vote down vote up
/**
 * Validates that a tmodel key is registered Alex O'Ree
 *
 * @param tmodelKey
 * @param em
 * @throws ValueNotAllowedException
 * @see org.apache.juddi.config.Install
 * @since 3.1.5
 */
private boolean verifyTModelKeyExistsAndChecked(String tmodelKey, Configuration config) throws ValueNotAllowedException {
        boolean checked = true;
        if (tmodelKey == null || tmodelKey.length() == 0) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:types")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:categorization:nodes")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_inquiry")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_publication")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_security")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_ownership_transfer")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscription")) {
                return false;
        }
        if (tmodelKey.equalsIgnoreCase("uddi:uddi.org:v3_subscriptionlistener")) {
                return false;
        }

        if (config == null) {
                log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullConfig"));
                return false;
        }
        boolean checkRef = false;
        try {
                checkRef = config.getBoolean(Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY, false);
        } catch (Exception ex) {
                log.warn("Error caught reading " + Property.JUDDI_ENFORCE_REFERENTIAL_INTEGRITY + " from config file", ex);
        }
        if (checkRef) {
                if (log.isDebugEnabled()) {
                        log.debug("verifyTModelKeyExists " + tmodelKey);
                }
                EntityManager em = PersistenceManager.getEntityManager();

                if (em == null) {
                        //this is normally the Install class firing up
                        log.warn(new ErrorMessage("errors.tmodel.ReferentialIntegrityNullEM"));
                } else {
                        //Collections.sort(buildInTmodels);
                        //if ((buildInTmodels, tmodelKey) == -1)
                        Tmodel modelTModel = null;
                        {
                                EntityTransaction tx = em.getTransaction();
                                try {

                                        tx.begin();
                                        modelTModel = em.find(org.apache.juddi.model.Tmodel.class, tmodelKey);

                                        if (modelTModel == null) {
                                                checked = false;
                                        } else {
                                             if (modelTModel.getCategoryBag()!=null)
                                                for (org.apache.juddi.model.KeyedReference ref : modelTModel.getCategoryBag().getKeyedReferences()) {
                                                        if ("uddi-org:types:unchecked".equalsIgnoreCase(ref.getKeyName())) {
                                                                checked = false;
                                                                break;
                                                        }
                                                }
                                        }

                                        tx.commit();

                                } finally {
                                        if (tx.isActive()) {
                                                tx.rollback();
                                        }
                                        em.close();
                                }
                                if (modelTModel == null) {
                                        throw new ValueNotAllowedException(new ErrorMessage("errors.tmodel.ReferencedKeyDoesNotExist", tmodelKey));
                                }
                        }
                }
        }
        return checked;
}