Java Code Examples for javax.persistence.EntityTransaction#begin()
The following examples show how to use
javax.persistence.EntityTransaction#begin() .
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: DatabaseAccessTokenStorage.java From jerseyoauth2 with MIT License | 6 votes |
protected void saveTokenEntity(TokenEntity te) { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.persist(te); em.flush(); tx.commit(); } catch (PersistenceException ex) { LOGGER.error("persistence error", ex); tx.rollback(); throw ex; } finally { em.close(); } }
Example 2
Source File: MultipleTransactionsPerEntityManagerTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
@Test public void test() { EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = entityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); entityManager.persist(new BlogEntityProvider.Post(1L)); txn.commit(); txn.begin(); entityManager.persist(new BlogEntityProvider.Post(2L)); txn.commit(); } catch (RuntimeException e) { if ( txn != null && txn.isActive()) txn.rollback(); throw e; } finally { if (entityManager != null) { entityManager.close(); } } }
Example 3
Source File: SalesOrderProcessor.java From cloud-espm-v2 with Apache License 2.0 | 6 votes |
/** * Function Import implementation for updating SalesOrderHeader */ private void updateSalesOrderHeader(String reportPath, List<SalesOrderItem> soiList, EntityManager em) { if (soiList != null && !soiList.isEmpty()) { EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); // add the path to the SalesOrder for (SalesOrderItem orderItem : soiList) { orderItem.getSalesOrderHeader().setInvoiceLink(reportPath); // save the soiList. em.merge(orderItem); } } finally { if(transaction!=null){ transaction.commit(); } } } }
Example 4
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 5
Source File: NotStandardTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 6 votes |
private 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 6
Source File: InfinispanHibernateCacheSpringLocal.java From infinispan-simple-tutorials with Apache License 2.0 | 6 votes |
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: JpaTest.java From code with Apache License 2.0 | 6 votes |
/** * 查询策略:使用立即加载策略 * 不管查询的对象是否使用,都会执行查询sql语句:先输出sql语句,再输出true; */ @Test public void testGetOne() { EntityManager em = null; EntityTransaction tx = null; try { // 1、获取EntityManager em = JpaUtil.getEntityManager(); // 2、获取事务 tx = em.getTransaction(); // 3、开启事务 tx.begin(); // 4、获取数据 // primaryKey类型必须和实体主键类型一致,否则查询不到 Customer c1 = em.find(Customer.class, 2L); Customer c2 = em.find(Customer.class, 2L); System.out.println(c1 == c2); // 5、提交事务 tx.commit(); System.out.println(c1); } catch (Exception e) { if (tx != null) tx.rollback(); } finally { if (em != null) em.close(); } }
Example 8
Source File: JPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
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 9
Source File: InumService.java From oxTrust with MIT License | 5 votes |
/** * Add an Inum to the DB * * @return True if user exist */ public boolean addInum(EntityManager inumEntryManager, String inum, String type) { boolean successs = false; EntityTransaction entityTransaction = inumEntryManager.getTransaction(); entityTransaction.begin(); try { // Prepare inum InumSqlEntry inumEntry = new InumSqlEntry(); inumEntry.setInum(inum); inumEntry.setType(type); // add inum inumEntryManager.persist(inumEntry); successs = true; } finally { if (successs) { // Commit transaction entityTransaction.commit(); } else { // Rollback transaction entityTransaction.rollback(); } } return successs; }
Example 10
Source File: GenericDAO.java From Truck-Factor with MIT License | 5 votes |
public void persist(T o) { EntityTransaction tx = this.em.getTransaction(); try { tx.begin(); this.em.persist(o); tx.commit(); } catch (RuntimeException e) { if(tx != null && tx.isActive()) tx.rollback(); throw e; } }
Example 11
Source File: JPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 5 votes |
private static void storeTestPersons(final EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); persistNewPerson(em, "Gizmo"); persistNewPerson(em, "Quarkus"); persistNewPerson(em, "Hibernate ORM"); transaction.commit(); em.close(); }
Example 12
Source File: JPAPersistenceStrategy.java From lams with GNU General Public License v2.0 | 5 votes |
public ACL createACL(Resource resource, Collection<ACLEntry> entries) { if (resource == null) throw PicketBoxMessages.MESSAGES.invalidNullArgument("resource"); // check the cache first. ACL acl = this.aclMap.get(resource); if (acl == null) { EntityManager entityManager = this.managerFactory.createEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { // create a new ACL and persist it to the database. acl = new ACLImpl(resource, entries); entityManager.persist(acl); // add the newly-created ACL to the cache. this.aclMap.put(resource, acl); transaction.commit(); } catch (RuntimeException re) { re.printStackTrace(); transaction.rollback(); } finally { entityManager.close(); } } return acl; }
Example 13
Source File: JPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 5 votes |
private static void deleteAllPerson(final EntityManagerFactory emf) { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); em.createNativeQuery("Delete from Person").executeUpdate(); transaction.commit(); em.close(); }
Example 14
Source File: DatabaseAccessTokenStorage.java From jerseyoauth2 with MIT License | 5 votes |
@Override public List<IAccessTokenInfo> invalidateTokensForUser(IUser user) { EntityManager em = emf.createEntityManager(); TypedQuery<TokenEntity> query = em.createNamedQuery("findTokenEntityByUsername", TokenEntity.class); query.setParameter("username", user.getName()); List<TokenEntity> resultList = query.getResultList(); List<IAccessTokenInfo> result = new LinkedList<>(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); for (TokenEntity te : resultList) { em.remove(te); result.add(te); } em.flush(); tx.commit(); LOGGER.debug("tokens for user {} invalidated", user.getName()); } catch (PersistenceException ex) { LOGGER.error("persistence error", ex); tx.rollback(); throw ex; } finally { em.close(); } return result; }
Example 15
Source File: RoutersService.java From galeb with Apache License 2.0 | 5 votes |
private void deleteHasChangeAndEntityFromDB(String envId, HasChangeData<String, String, String> hasChangeData, String logCorrelation) { String entityClass = hasChangeData.entityClassName(); String entityId = hasChangeData.entityId(); final EntityManager entityManager = entityManagerFactory.createEntityManager(); final EntityTransaction transaction = entityManager.getTransaction(); final JsonEventToLogger event = new JsonEventToLogger(this.getClass()); event.put("correlation", logCorrelation); event.put("entityId", entityId); event.put("entityClass", entityClass); event.put("environmentId", envId); try { transaction.begin(); Query query = entityManager.createQuery("DELETE FROM " + entityClass + " e WHERE e.id = :entityId AND e.quarantine = true"); query.setParameter("entityId", Long.parseLong(entityId)); int numEntities = query.executeUpdate(); transaction.commit(); if (numEntities > 0) { event.put("short_message", "Delete HasChange and Entity from DB"); event.sendInfo(); } changesService.delete(hasChangeData.key()); } catch (Exception e) { transaction.rollback(); event.put("short_message", "Delete HasChange and Entity from DB FAILED"); event.sendError(e); } finally { entityManager.close(); } }
Example 16
Source File: AbstractModelTest.java From pnc with Apache License 2.0 | 5 votes |
/** * 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 17
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 5 votes |
private static void testDeleteViaRemove(final EntityManagerFactory emf) { Statistics stats = getStatistics(emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); em.remove(em.find(Pokemon.class, 3)); em.remove(em.find(Pokemon.class, 248)); em.remove(em.find(Pokemon.class, 242)); transaction.commit(); em.close(); assertRegionStats(new Counts(0, 3, 0, 4), Pokemon.class.getName(), stats); stats = getStatistics(emf); em = emf.createEntityManager(); transaction = em.getTransaction(); transaction.begin(); if (em.find(Pokemon.class, 3) != null || em.find(Pokemon.class, 248) != null || em.find(Pokemon.class, 242) != null) { throw new RuntimeException("Pokemons should have been deleted"); } transaction.commit(); em.close(); assertRegionStats(new Counts(0, 0, 3, 4), Pokemon.class.getName(), stats); }
Example 18
Source File: UserTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void testDetach(){ String name = "foo"; User user = new User(); user.setName(name); assertTrue(persistInATransaction(user)); assertTrue(em.contains(user)); em.detach(user); assertFalse(em.contains(user)); //"refresh" fails, as entity is detached EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.refresh(user); tx.commit(); fail(); } catch (Exception e){ tx.rollback(); } //being detached from the EntityManager does not mean being removed from DB User found = em.find(User.class, user.getId()); assertEquals(name, found.getName()); }
Example 19
Source File: IdCreationTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 4 votes |
@Test public void testIdPersistence(){ EntityManagerFactory factory = Persistence.createEntityManagerFactory("DB");//same name as in persistence.xml EntityManager em = factory.createEntityManager();//it works as a cache/buffer until we commit a transaction User01 user01 = new User01(); user01.setName("AName"); user01.setSurname("ASurname"); // by default, no id, until data committed to the database assertNull(user01.getId()); //committing data to database needs to be inside a transaction EntityTransaction tx = em.getTransaction(); tx.begin(); try{ /* The following is actually executing this SQL statement: insert into User01 (name, surname, id) values (?, ?, ?) */ em.persist(user01); //there can be several operations on the "cache" EntityManager before we actually commit the transaction tx.commit(); } catch (Exception e){ //abort the transaction if there was any exception tx.rollback(); fail();//fail the test } finally { //in any case, make sure to close the opened resources em.close(); factory.close(); } //id should have now be set assertNotNull(user01.getId()); System.out.println("GENERATED ID: "+user01.getId()); }
Example 20
Source File: Install.java From juddi with Apache License 2.0 | 4 votes |
protected static void install(Configuration config) throws JAXBException, DispositionReportFaultMessage, IOException, ConfigurationException, XMLStreamException { EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); UddiEntityPublisher rootPublisher = null; try { tx.begin(); boolean seedAlways = config.getBoolean("juddi.seed.always", false); boolean alreadyInstalled = alreadyInstalled(config); if (!seedAlways && alreadyInstalled) { throw new FatalErrorException(new ErrorMessage("errors.install.AlreadyInstalled")); } String rootPublisherStr = config.getString(Property.JUDDI_ROOT_PUBLISHER); String fileRootTModelKeygen = rootPublisherStr + FILE_TMODELKEYGEN; TModel rootTModelKeyGen = (TModel) buildInstallEntity(fileRootTModelKeygen, "org.uddi.api_v3", config); String fileRootBusinessEntity = rootPublisherStr + FILE_BUSINESSENTITY; org.uddi.api_v3.BusinessEntity rootBusinessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileRootBusinessEntity, "org.uddi.api_v3", config); String rootPartition = getRootPartition(rootTModelKeyGen); //JUDDI-645 String nodeId = config.getString(Property.JUDDI_NODE_ID, getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition)); //getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); String rootbizkey = getNodeId(rootBusinessEntity.getBusinessKey(), rootPartition); String fileRootPublisher = rootPublisherStr + FILE_PUBLISHER; String fileReplicationConfig = rootPublisherStr + FILE_REPLICATION_CONFIG; org.uddi.repl_v3.ReplicationConfiguration replicationCfg = (org.uddi.repl_v3.ReplicationConfiguration) buildInstallEntityAlt(fileReplicationConfig, org.uddi.repl_v3.ReplicationConfiguration.class, config); if (!alreadyInstalled) { log.info("Loading the root Publisher from file " + fileRootPublisher); rootPublisher = installPublisher(em, fileRootPublisher, config); installRootPublisherKeyGen(em, rootTModelKeyGen, rootPartition, rootPublisher, nodeId); rootBusinessEntity.setBusinessKey(rootbizkey); installBusinessEntity(true, em, rootBusinessEntity, rootPublisher, rootPartition, config, nodeId); installReplicationConfiguration(em, replicationCfg, config, nodeId); } else { log.debug("juddi.seed.always reapplies all seed files except for the root data."); } List<String> juddiPublishers = getPublishers(config); for (String publisherStr : juddiPublishers) { String filePublisher = publisherStr + FILE_PUBLISHER; String fileTModelKeygen = publisherStr + FILE_TMODELKEYGEN; TModel tModelKeyGen = (TModel) buildInstallEntity(fileTModelKeygen, "org.uddi.api_v3", config); String fileBusinessEntity = publisherStr + FILE_BUSINESSENTITY; org.uddi.api_v3.BusinessEntity businessEntity = (org.uddi.api_v3.BusinessEntity) buildInstallEntity(fileBusinessEntity, "org.uddi.api_v3", config); UddiEntityPublisher publisher = installPublisher(em, filePublisher, config); if (publisher == null) { throw new ConfigurationException("File " + filePublisher + " not found."); } else { if (tModelKeyGen != null) { installPublisherKeyGen(em, tModelKeyGen, publisher, nodeId); } if (businessEntity != null) { installBusinessEntity(false, em, businessEntity, publisher, null, config, nodeId); } String fileTModels = publisherStr + FILE_TMODELS; installSaveTModel(em, fileTModels, publisher, nodeId, config); } } tx.commit(); } catch (DispositionReportFaultMessage dr) { log.error(dr.getMessage(), dr); tx.rollback(); throw dr; } catch (JAXBException je) { log.error(je.getMessage(), je); tx.rollback(); throw je; } catch (IOException ie) { log.error(ie.getMessage(), ie); tx.rollback(); throw ie; } catch (XMLStreamException ex) { log.error(ex.getMessage(), ex); tx.rollback(); throw ex; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }