Java Code Examples for javax.persistence.EntityTransaction#commit()
The following examples show how to use
javax.persistence.EntityTransaction#commit() .
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: AWSResourceRequirementRepository.java From testgrid with Apache License 2.0 | 6 votes |
/** * Persists an {@link AWSResourceRequirement} instance in the database. * * @param resourceRequirementList The list of {@link AWSResourceRequirement} to persist to the database * @throws TestGridDAOException thrown when error on persisting */ public void persistResourceRequirements(List<AWSResourceRequirement> resourceRequirementList) throws TestGridDAOException { String selectQuery = "SELECT * FROM aws_resource_requirement WHERE cfn_md5_hash=? FOR UPDATE;"; List resultList; try { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); resultList = entityManager.createNativeQuery(selectQuery, AWSResourceRequirement.class) .setParameter(1, resourceRequirementList.get(0).getCfnMD5Hash()) .getResultList(); if (!resultList.isEmpty()) { resourceRequirementList = EntityManagerHelper.refreshResultList(entityManager, resultList); } for (AWSResourceRequirement resourceRequirement : resourceRequirementList) { entityManager.persist(resourceRequirement); } transaction.commit(); } catch (Exception e) { throw new TestGridDAOException("Error while executing query in database", e); } }
Example 2
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 3
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 4
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 5
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java From quarkus with Apache License 2.0 | 6 votes |
private static Statistics verifyFindCountryByNaturalId(EntityManagerFactory emf, String callingCode, String expectedName) { Statistics stats = getStatistics(emf); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); transaction.begin(); final Session session = em.unwrap(Session.class); final NaturalIdLoadAccess<Country> loader = session.byNaturalId(Country.class); loader.using("callingCode", callingCode); Country country = loader.load(); if (!country.getName().equals(expectedName)) throw new RuntimeException("Incorrect citizen: " + country.getName() + ", expected: " + expectedName); transaction.commit(); em.close(); return stats; }
Example 6
Source File: TestBase.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 7
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 8
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 9
Source File: TransactionExecutor.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 6 votes |
private Thread createThread(Consumer<EntityManager> command) { return new Thread(() ->{ EntityManager em = factory.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try{ command.accept(em); tx.commit(); } catch (Exception e){ tx.rollback(); System.out.println("\n\nFailed transaction on separated thread: "+e.getCause().toString()+"\n\n"); } em.close(); }); }
Example 10
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 11
Source File: InumService.java From oxTrust with MIT License | 5 votes |
/** * get an inum from inum DB by inum value * * @return InumSqlEntry */ public InumSqlEntry findInumByObject(EntityManager inumEntryManager, String inum) { boolean successs = false; EntityTransaction entityTransaction = inumEntryManager.getTransaction(); entityTransaction.begin(); InumSqlEntry result = null; try { InumSqlEntry tempInum = new InumSqlEntry(); tempInum.setInum(inum); // find inum result = inumEntryManager.find(InumSqlEntry.class, tempInum); if (result != null) { successs = true; } } finally { if (successs) { // Commit transaction entityTransaction.commit(); } else { // Rollback transaction entityTransaction.rollback(); } } return result; }
Example 12
Source File: UserTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void testRefresh(){ String before = "before"; String after = "after"; User user = new User(); user.setName(before); assertTrue(persistInATransaction(user)); user.setName(after); assertEquals(after, user.getName()); //we can only do a "refresh" on a managed entity, not detached ones //em.clear(); //now we "refresh" the changes done after the transaction EntityTransaction tx = em.getTransaction(); em.contains(user); tx.begin(); em.refresh(user); //this practically update the entity with values from the DB tx.commit(); em.clear(); assertEquals(before, user.getName()); }
Example 13
Source File: InsertTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
private boolean persistInATransaction(Object obj) { EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.persist(obj); tx.commit(); } catch (Exception e) { System.out.println("FAILED TRANSACTION: " + e.toString()); tx.rollback(); return false; } return true; }
Example 14
Source File: UserTest.java From testing_security_development_enterprise_systems with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void testOrphanRemovalOwner(){ Address address = new Address(); User user = new User(); user.setAddress(address); //User refers to unmanaged Address, and no cascade for persist assertFalse(persistInATransaction(user)); user.setId(null); assertTrue(persistInATransaction(user,address)); Address found = em.find(Address.class, address.getId()); assertNotNull(found); //now remove User from DB EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.remove(user); tx.commit(); } catch (Exception e){ tx.rollback(); //throw Error, and so fail test if this is reached fail(); } //User is owner of the OneToOne relation, so, because of "orphanRemoval, //address get removed as well found = em.find(Address.class, address.getId()); assertNull(found); }
Example 15
Source File: JpaUtil.java From code with Apache License 2.0 | 5 votes |
public static void jpaTemplate(Callback callback) { EntityManager em = null; EntityTransaction tx = null; try { // 1、获取EntityManager em = JpaUtil.getEntityManager(); // 2、获取事务 tx = em.getTransaction(); // 3、开启事务 tx.begin(); // do somethings callback.execute(em); // 5、提交事务 tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { if (em != null) { em.close(); } } }
Example 16
Source File: RESTApiFacadeImpl.java From zstack with Apache License 2.0 | 5 votes |
private RestAPIVO find(String uuid) { EntityManager mgr = getEntityManager(); EntityTransaction tran = mgr.getTransaction(); try { tran.begin(); RestAPIVO vo = mgr.find(RestAPIVO.class, uuid); tran.commit(); return vo; } catch (Exception e) { tran.rollback(); throw new CloudRuntimeException(e); } finally { mgr.close(); } }
Example 17
Source File: JPAProcessorImplTest.java From olingo-odata2 with Apache License 2.0 | 5 votes |
private EntityTransaction getLocalTransaction() { EntityTransaction entityTransaction = EasyMock.createMock(EntityTransaction.class); entityTransaction.begin(); // testing void method entityTransaction.begin(); // testing void method entityTransaction.commit();// testing void method entityTransaction.commit();// testing void method EasyMock.expect(entityTransaction.isActive()).andReturn(false).anyTimes(); EasyMock.replay(entityTransaction); return entityTransaction; }
Example 18
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 19
Source File: CiServiceImpl.java From we-cmdb with Apache License 2.0 | 4 votes |
@OperationLogPointcut(operation = Modification, objectClass = CiData.class) @Override public List<Map<String, Object>> update(@CiTypeId int ciTypeId,@CiDataType List<Map<String, Object>> cis) { if (logger.isDebugEnabled()) { logger.debug("CIs update request, ciTypeId:{}, query request:{}", ciTypeId, JsonUtil.toJsonString(cis)); } validateDynamicEntityManager(); List<Map<String, Object>> rtnCis = new LinkedList<>(); List<ExceptionHolder> exceptionHolders = new LinkedList<>(); PriorityEntityManager priEntityManager = getEntityManager(); EntityManager entityManager = priEntityManager.getEntityManager(); try { EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); try { for (Map<String, Object> ci : cis) { String callbackId = null; if (ci.get(CALLBACK_ID) != null) { callbackId = ci.get(CALLBACK_ID).toString(); } try { ci.remove(CALLBACK_ID); validateCiType(ciTypeId); validateUpdateCiData(ciTypeId, ci); validateCiData(ciTypeId, ci, true); DynamicEntityMeta entityMeta = getDynamicEntityMetaMap().get(ciTypeId); Map<String, Object> updatedDomainMap = doUpdate(entityManager, ciTypeId, ci, true); Map<String, Object> enhacedMap = enrichCiObject(entityMeta, updatedDomainMap, entityManager); enhacedMap.put(CALLBACK_ID, callbackId); rtnCis.add(enhacedMap); } catch (Exception e) { String errorMessage = String.format("Fail to update ci data ciTypeId [%s], error [%s]", ciTypeId, ExceptionHolder.extractExceptionMessage(e)); logger.warn(errorMessage, e); ci.put(CALLBACK_ID, callbackId); exceptionHolders.add(new ExceptionHolder(callbackId, ci, errorMessage, e)); } } if (exceptionHolders.size() == 0) { transaction.commit(); } else { transaction.rollback(); throw new BatchChangeException(String.format("Fail to update [%d] records, detail error in the data block", exceptionHolders.size()), exceptionHolders); } } catch (Exception exc) { if (exc instanceof BatchChangeException) { throw exc; } else { transaction.rollback(); throw new ServiceException("Failed to update ci data.", exc); } } } finally { priEntityManager.close(); } if (logger.isDebugEnabled()) { logger.debug("Return ci response:{}", JsonUtil.toJsonString(rtnCis)); } return rtnCis; }
Example 20
Source File: UDDIPublicationImplExt.java From juddi with Apache License 2.0 | 4 votes |
public BusinessDetail saveBusinessFudge(SaveBusiness body, String nodeID) throws DispositionReportFaultMessage { if (!body.getBusinessEntity().isEmpty()) { log.debug("Inbound save business Fudger request for key " + body.getBusinessEntity().get(0).getBusinessKey()); } EntityManager em = PersistenceManager.getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo()); ValidatePublish validator = new ValidatePublish(publisher); validator.validateSaveBusiness(em, body, null, publisher); BusinessDetail result = new BusinessDetail(); List<org.uddi.api_v3.BusinessEntity> apiBusinessEntityList = body.getBusinessEntity(); for (org.uddi.api_v3.BusinessEntity apiBusinessEntity : apiBusinessEntityList) { org.apache.juddi.model.BusinessEntity modelBusinessEntity = new org.apache.juddi.model.BusinessEntity(); MappingApiToModel.mapBusinessEntity(apiBusinessEntity, modelBusinessEntity); nodeId = nodeID; setOperationalInfo(em, modelBusinessEntity, publisher); em.persist(modelBusinessEntity); result.getBusinessEntity().add(apiBusinessEntity); } //check how many business this publisher owns. validator.validateSaveBusinessMax(em); tx.commit(); return result; } catch (DispositionReportFaultMessage drfm) { throw drfm; } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }