javax.persistence.EntityTransaction Java Examples
The following examples show how to use
javax.persistence.EntityTransaction.
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: JPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void verifyJPANamedQuery(final EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); TypedQuery<Person> typedQuery = em.createNamedQuery( "get_person_by_name", Person.class); typedQuery.setParameter("name", "Quarkus"); final Person singleResult = typedQuery.getSingleResult(); if (!singleResult.getName().equals("Quarkus")) { throw new RuntimeException("Wrong result from named JPA query"); } transaction.commit(); em.close(); }
Example #2
Source File: JpaTest.java From code with Apache License 2.0 | 6 votes |
@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 #3
Source File: BasicModelTest.java From pnc with Apache License 2.0 | 6 votes |
@Test public void testProductVersionBrewTagGeneration() { EntityManager em = getEmFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); final String version = "10.1"; Product product = Product.Builder.newBuilder().id(1).build(); ProductVersion productVersionOriginal = ProductVersion.Builder.newBuilder() .version(version) .product(product) .generateBrewTagPrefix("TP1", version, "${product_short_name}-${product_version}-pnc") .build(); tx.begin(); em.persist(productVersionOriginal); tx.commit(); ProductVersion productVersionLoaded = em.find(ProductVersion.class, productVersionOriginal.getId()); Assert.assertEquals( "tp1-" + version + "-pnc", productVersionLoaded.getAttributes().get(Attributes.BREW_TAG_PREFIX)); }
Example #4
Source File: TransactionSupport.java From jpa-unit with Apache License 2.0 | 6 votes |
private <R, T> R execute(final Function<T, R> function) { final EntityTransaction tx = em.getTransaction(); final boolean wasActive = beforeTransactionBegin(tx); try { transactionBegin(tx); final R ret = function.apply(null); transactionCommit(tx); if (flushOnCommit) { em.flush(); } if (clearOnCommit) { em.clear(); } return ret; } finally { afterTransactionCommit(tx, wasActive); } }
Example #5
Source File: LdapExpandedAuthenticator.java From juddi with Apache License 2.0 | 6 votes |
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 #6
Source File: JBossAuthenticator.java From juddi with Apache License 2.0 | 6 votes |
public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); Publisher publisher = null; try { tx.begin(); publisher = em.find(Publisher.class, authorizedName); if (publisher == null) throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName)); AuthToken at = em.find(AuthToken.class, authInfo); if (at == null) throw new AuthTokenRequiredException(new ErrorMessage("E_authTokenRequired", authInfo)); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } return publisher; }
Example #7
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 #8
Source File: DBAuditDestination.java From ranger with Apache License 2.0 | 6 votes |
private boolean rollbackTransaction() { boolean ret = false; EntityTransaction trx = null; try { trx = getTransaction(); if (trx != null && trx.isActive()) { trx.rollback(); ret = true; } else { throw new Exception("trx is null or not active"); } } catch (Throwable excp) { logger.error("DBAuditDestination.rollbackTransaction(): failed", excp); cleanUp(); // so that next insert will try to init() } finally { clearEntityManager(); } return ret; }
Example #9
Source File: JPARecipientRewriteTable.java From james-project with Apache License 2.0 | 6 votes |
/** * Remove a mapping for the given user and domain */ private void doRemoveMapping(MappingSource source, String mapping) throws RecipientRewriteTableException { EntityManager entityManager = entityManagerFactory.createEntityManager(); final EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); entityManager.createNamedQuery("deleteMapping") .setParameter("user", source.getFixedUser()) .setParameter("domain", source.getFixedDomain()) .setParameter("targetAddress", mapping) .executeUpdate(); transaction.commit(); } catch (PersistenceException e) { LOGGER.debug("Failed to remove mapping", e); if (transaction.isActive()) { transaction.rollback(); } throw new RecipientRewriteTableException("Unable to remove mapping", e); } finally { EntityManagerUtils.safelyClose(entityManager); } }
Example #10
Source File: DbAuditProvider.java From ranger with Apache License 2.0 | 6 votes |
private boolean commitTransaction() { boolean ret = false; EntityTransaction trx = null; try { trx = getTransaction(); if(trx != null && trx.isActive()) { trx.commit(); ret =true; } else { throw new Exception("trx is null or not active"); } } catch(Exception excp) { logDbError("DbAuditProvider.commitTransaction(): failed", excp); cleanUp(); // so that next insert will try to init() } finally { clearEntityManager(); } return ret; }
Example #11
Source File: CustomerDB.java From MusicStore with MIT License | 6 votes |
/** * @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 #12
Source File: JPAUsersDAO.java From james-project with Apache License 2.0 | 6 votes |
/** * Removes a user from the repository * * @param name * the user to remove from the repository */ @Override public void removeUser(Username name) throws UsersRepositoryException { EntityManager entityManager = entityManagerFactory.createEntityManager(); final EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); if (entityManager.createNamedQuery("deleteUserByName").setParameter("name", name.asString()).executeUpdate() < 1) { transaction.commit(); throw new UsersRepositoryException("User " + name.asString() + " does not exist"); } else { transaction.commit(); } } catch (PersistenceException e) { LOGGER.debug("Failed to remove user", e); if (transaction.isActive()) { transaction.rollback(); } throw new UsersRepositoryException("Failed to remove user " + name.asString(), e); } finally { EntityManagerUtils.safelyClose(entityManager); } }
Example #13
Source File: JPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void verifyJPANamedQuery(final EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); TypedQuery<Person> typedQuery = em.createNamedQuery( "get_person_by_name", Person.class); typedQuery.setParameter("name", "Quarkus"); final Person singleResult = typedQuery.getSingleResult(); if (!singleResult.getName().equals("Quarkus")) { throw new RuntimeException("Wrong result from named JPA query"); } transaction.commit(); em.close(); }
Example #14
Source File: JUDDIAuthenticator.java From juddi with Apache License 2.0 | 6 votes |
public UddiEntityPublisher identify(String authInfo, String authorizedName, WebServiceContext ctx) throws AuthenticationException { 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 #15
Source File: AppExtension.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
@Override public void afterTestExecution(ExtensionContext context) throws Exception { ExtensionContext.Store store = context.getStore(ExtensionContext.Namespace.create(AppExtension.class, MockApp.class)); MockApp app = (MockApp) store.get(MockApp.class); if (app.isInstalled("jweb.database")) { AbstractModule module = app.module("jweb.database"); Database database = module.require(Database.class); EntityManager em = database.em(); EntityTransaction transaction = em.getTransaction(); try { logger.info("reset database"); transaction.begin(); em.createNativeQuery(HSQL_RESET_SQL).executeUpdate(); } catch (Exception e) { logger.error("failed to reset database", e); } finally { transaction.commit(); em.close(); } } }
Example #16
Source File: TransactionalInterceptor.java From BeanTest with Apache License 2.0 | 6 votes |
@AroundInvoke public Object manageTransaction(InvocationContext ctx) throws Exception { EntityTransaction transaction = em.getTransaction(); if (!transaction.isActive()) { transaction.begin(); LOGGER.debug("Transaction started"); } INTERCEPTOR_COUNTER++; Object result = null; try { result = ctx.proceed(); } catch (Exception e) { if (isFirstInterceptor()) { markRollbackTransaction(e); } throw e; } finally { processTransaction(); } return result; }
Example #17
Source File: JPAUtil.java From juddi with Apache License 2.0 | 6 votes |
public static void deleteEntity(Class<?> entityClass, Object entityKey) { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); Object obj = em.find(entityClass, entityKey); em.remove(obj); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
Example #18
Source File: JPARecipientRewriteTable.java From james-project with Apache License 2.0 | 6 votes |
/** * Add mapping for given user and domain */ private void doAddMapping(MappingSource source, String mapping) throws RecipientRewriteTableException { EntityManager entityManager = entityManagerFactory.createEntityManager(); final EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); JPARecipientRewrite jpaRecipientRewrite = new JPARecipientRewrite(source.getFixedUser(), Domain.of(source.getFixedDomain()), mapping); entityManager.persist(jpaRecipientRewrite); transaction.commit(); } catch (PersistenceException e) { LOGGER.debug("Failed to save virtual user", e); if (transaction.isActive()) { transaction.rollback(); } throw new RecipientRewriteTableException("Unable to add mapping", e); } finally { EntityManagerUtils.safelyClose(entityManager); } }
Example #19
Source File: DownloadDB.java From MusicStore with MIT License | 6 votes |
/** * 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 #20
Source File: JPAOAuthDataProvider.java From cxf with Apache License 2.0 | 6 votes |
protected <T> T executeInTransaction(EntityManagerOperation<T> operation) { EntityManager em = getEntityManager(); EntityTransaction transaction = null; T value; try { transaction = beginIfNeeded(em); value = operation.apply(em); flushIfNeeded(em); commitIfNeeded(em); } catch (RuntimeException e) { if (transaction != null) { transaction.rollback(); } throw e; } finally { closeIfNeeded(em); } return value; }
Example #21
Source File: DatabaseImplTest.java From jweb-cms with GNU Affero General Public License v3.0 | 6 votes |
@BeforeEach void setup() { database = database(); database.addEntityClassName(TestEntity.class); database.addEntityClassName(TestView.class); database.start(); EntityManager em = database.em(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); try { TestEntity entity = new TestEntity(); entity.id = UUID.randomUUID().toString(); em.persist(entity); } finally { transaction.commit(); em.close(); } }
Example #22
Source File: RESTApiFacadeImpl.java From zstack with Apache License 2.0 | 6 votes |
private RestAPIVO persist(APIMessage msg) { RestAPIVO vo = new RestAPIVO(); vo.setUuid(msg.getId()); vo.setApiMessageName(msg.getMessageName()); vo.setState(RestAPIState.Processing); EntityManager mgr = getEntityManager(); EntityTransaction tran = mgr.getTransaction(); try { tran.begin(); mgr.persist(vo); mgr.flush(); mgr.refresh(vo); tran.commit(); return vo; } catch (Exception e) { ExceptionDSL.exceptionSafe(tran::rollback); throw new CloudRuntimeException(e); } finally { ExceptionDSL.exceptionSafe(mgr::close); } }
Example #23
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void verifyReadWriteCollection(final EntityManagerFactory emf, int expectedSize, Map<String, Counts> counts) { Statistics stats = getStatistics(emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); final Trainer t1 = em.find(Trainer.class, 1L); final List<Pokemon> pokemons = t1.getPokemons(); if (pokemons.size() != expectedSize) throw new RuntimeException("Incorrect family size: " + pokemons.size() + ", expected: " + expectedSize); transaction.commit(); em.close(); assertRegionStats(counts, stats); }
Example #24
Source File: DefaultDatabase.java From BootsFaces-Examples with Apache License 2.0 | 6 votes |
public void populateUserTable(EntityManager entityManager) { EntityTransaction transaction = entityManager.getTransaction(); try { transaction.begin(); createUser(entityManager, "Robina Kuh", "[email protected]"); createUser(entityManager, "Wayne Interessierts", "[email protected]"); createUser(entityManager, "John Doe", "[email protected]"); createUser(entityManager, "Jane Dull", "[email protected]"); List<String> names = Names.getNames(); for (String name:names) { createUser(entityManager, name, name.replace(" ", ".")+"@example.com"); } transaction.commit(); } catch (Exception e) { transaction.rollback(); } }
Example #25
Source File: ClinicServiceImpl.java From activejpa with Apache License 2.0 | 6 votes |
@Override public void saveOwner(Owner owner) { EntityTransaction transaction = Owner.beginTxn(); boolean successful = false; try { owner.persist(); successful = true; } finally { if (transaction != null) { if (successful) { transaction.commit(); } else { transaction.rollback(); } } } }
Example #26
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void testDeleteViaQuery(final EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); em.createNativeQuery("Delete from Person").executeUpdate(); transaction.commit(); em.close(); Statistics stats = getStatistics(emf); em = emf.createEntityManager(); transaction = em.getTransaction(); transaction.begin(); if (em.find(Person.class, 1L) != null || em.find(Person.class, 2L) != null || em.find(Person.class, 3L) != null || em.find(Person.class, 4L) != null) { throw new RuntimeException("Persons should have been deleted"); } transaction.commit(); em.close(); assertRegionStats(new Counts(0, 0, 4, 0), Person.class.getName(), stats); }
Example #27
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void rebalanceCpsForPokemons(final EntityManagerFactory emf, Counts expected) { Statistics stats = getStatistics(emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); Pokemon igeldo = em.find(Pokemon.class, 3); igeldo.setCp(2707); Pokemon godzilla = em.find(Pokemon.class, 248); godzilla.setCp(3834); Pokemon blissey = em.find(Pokemon.class, 242); blissey.setCp(2757); transaction.commit(); em.close(); assertRegionStats(expected, Pokemon.class.getName(), stats); }
Example #28
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static void storeTestPokemons(final EntityManagerFactory emf, Counts expected) { Statistics stats = getStatistics(emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); final Pokemon igeldo = new Pokemon(3, "Venusaur", 2555); em.persist(igeldo); final Pokemon godzilla = new Pokemon(248, "Tyranitar", 3670); em.persist(godzilla); final Pokemon khaleesi = new Pokemon(242, "Blissey", 3219); em.persist(khaleesi); transaction.commit(); em.close(); assertRegionStats(expected, Pokemon.class.getName(), stats); }
Example #29
Source File: EntityTestBase.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 6 votes |
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 #30
Source File: PersistenceContextExtendedBatchTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
private void withBatch() { int entityCount = 20; EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = entityManagerFactory().createEntityManager(); entityManager.unwrap(Session.class).setJdbcBatchSize(10); txn = entityManager.getTransaction(); txn.begin(); int entityManagerBatchSize = 20; for ( long i = 0; i < entityCount; ++i ) { Post person = new Post( i, String.format( "Post nr %d", i )); entityManager.persist( person ); if ( i > 0 && i % entityManagerBatchSize == 0 ) { entityManager.flush(); entityManager.clear(); } } txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive()) { txn.rollback(); } throw e; } finally { if (entityManager != null) { entityManager.close(); } } }