List of usage examples for javax.persistence EntityManager flush
public void flush();
From source file:com.webbfontaine.valuewebb.action.tt.TtLogger.java
private void persistLog(TtLog ttLog) { EntityManager entityManager = null; try {// w w w . j a v a 2 s .c om entityManager = Utils.createEntityManager(); entityManager.persist(ttLog); entityManager.flush(); } finally { if (entityManager != null) { entityManager.close(); } } }
From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployerRepositoryImplementation.java
@Override public boolean update(Employer employer) { EntityManager em = entityManagerFactory.createEntityManager(); boolean success = true; try {//www . j a va 2 s .c om em.getTransaction().begin(); em.merge(employer); em.flush(); em.getTransaction().commit(); success = true; } catch (RuntimeException e) { Logger.getLogger(BasicSkillRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); success = false; } em.close(); } return success; }
From source file:com.webbfontaine.valuewebb.action.tt.TtLogger.java
public String deleteUserLog(TtLog log) { EntityManager entityManager = null; try {//from w w w .jav a 2 s. c o m entityManager = Utils.createEntityManager(); entityManager.remove(entityManager.merge(log)); entityManager.flush(); reloadLogs(log); } finally { if (entityManager != null) { entityManager.close(); } } return ""; }
From source file:controllers.modules.SetCoverBuilder.java
@BodyParser.Of(play.mvc.BodyParser.Json.class) public static Result update(final UUID corpus, UUID setcover) { DocumentCorpus corpusObj = null;/*from w ww.j a va 2 s . co m*/ if (corpus != null) { corpusObj = fetchResource(corpus, DocumentCorpus.class); } // make sure we have the right combination. DocumentSetCover setCoverObj = null; if (setcover != null) { setCoverObj = fetchResource(setcover, DocumentSetCover.class); if (corpusObj == null) { corpusObj = setCoverObj.getBaseCorpus(); } else if (ObjectUtils.notEqual(corpusObj, setCoverObj.getBaseCorpus())) { throw new IllegalArgumentException(); } } else if (corpusObj == null) { throw new IllegalArgumentException(); } JsonNode jsonBody = request().body().asJson(); if (jsonBody == null && setcover != null) { throw new IllegalArgumentException(); } if (jsonBody == null) { jsonBody = JsonNodeFactory.instance.objectNode(); } DocumentSetCoverModel setCoverVM = null; setCoverVM = Json.fromJson(jsonBody, DocumentSetCoverModel.class); final SetCoverFactory factory = (SetCoverFactory) setCoverVM.toFactory().setOwnerId(getUsername()); // set the default title. if (setcover == null && StringUtils.isEmpty(factory.getTitle())) { factory.setTitle("Optimized " + corpusObj.getTitle()); } SetCoverFactory tmpFactory = (SetCoverFactory) new SetCoverFactory().setStore(corpusObj) .setTitle(factory.getTitle()).setDescription(factory.getDescription()) .setOwnerId(factory.getOwnerId()); // make basic creation/updation first. if (setcover == null) { setCoverObj = tmpFactory.create(); em().persist(setCoverObj); setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj); // if this is a simple change, just return from here. if (ObjectUtils.equals( ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()), new TokenizingOptions()) && factory.getWeightCoverage() == SetCoverFactory.DEFAULT_WEIGHT_COVERAGE) { return created(setCoverVM.asJson()); } setcover = setCoverObj.getIdentifier(); } else if (!StringUtils.equals(StringUtils.defaultString(tmpFactory.getTitle(), setCoverObj.getTitle()), setCoverObj.getTitle()) || !StringUtils.equals( StringUtils.defaultString(tmpFactory.getDescription(), setCoverObj.getDescription()), setCoverObj.getDescription())) { tmpFactory.setEm(em()).setExistingId(setcover); setCoverObj = tmpFactory.create(); em().merge(setCoverObj); setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj); setCoverVM.populateSize(em(), setCoverObj); // if this is a simple change, just return from here. if (ObjectUtils.equals( ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()), ObjectUtils.defaultIfNull(setCoverObj.getTokenizingOptions(), new TokenizingOptions())) && ObjectUtils.equals(factory.getWeightCoverage(), ObjectUtils.defaultIfNull( setCoverObj.getWeightCoverage(), SetCoverFactory.DEFAULT_WEIGHT_COVERAGE))) { return ok(setCoverVM.asJson()); } } // get rid of any old progress observer tokens and create a new one. finalizeProgress(setCoverObj.getId()); createProgressObserverToken(setCoverObj.getId()); watchProgress(factory, "create", setCoverObj.getId()); final Context ctx = Context.current(); final UUID setCoverId = setcover; Akka.future(new Callable<DocumentSetCover>() { @Override public DocumentSetCover call() throws Exception { try { return execute(new SareTxRunnable<DocumentSetCover>() { @Override public DocumentSetCover run(EntityManager em) throws Throwable { bindEntityManager(em); Context.current.set(ctx); DocumentSetCover setCoverObj = null; UUID corpusId = corpus; if (corpusId == null) { setCoverObj = fetchResource(setCoverId, DocumentSetCover.class); corpusId = setCoverObj.getBaseCorpus().getIdentifier(); } factory.setStore(fetchResource(corpusId, DocumentCorpus.class)) .setExistingId(setCoverId).setEm(em); List<SetCoverDocument> oldDocuments = Lists.newArrayList(setCoverObj.getAllDocuments()); setCoverObj = factory.create(); em.flush(); em.merge(setCoverObj); em.getTransaction().commit(); em.clear(); em.getTransaction().begin(); for (SetCoverDocument oldDocument : oldDocuments) { if (Iterables.find(setCoverObj.getAllDocuments(), Predicates.equalTo(oldDocument), null) == null) { SetCoverDocument tmpDocument = em.find(SetCoverDocument.class, oldDocument.getId()); em.remove(tmpDocument); } } return setCoverObj; } }, ctx); } catch (Throwable e) { Logger.error(LoggedAction.getLogEntry(ctx, "failed to build set cover"), e); throw new IllegalArgumentException(e); } finally { setProgressFinished(UuidUtils.toBytes(setCoverId)); } } }); return ok(setCoverVM.asJson()); }
From source file:org.eclipse.jubula.client.core.persistence.TestResultPM.java
/** * deleting monitoring reports by age (days of existence) * or deleting all, if the summaryId is null. * @param session The current session (EntityManager) * @param summaryId The summaryToDelete. * This value can be null, if all test results were deleted. * if summaryId is null, all monitoring reports will also be deleted. *//*from ww w . ja va 2 s. c om*/ private static void deleteMonitoringReports(EntityManager session, Long summaryId) { ITestResultSummaryPO summaryPo = null; if (summaryId != null) { summaryPo = session.find(PoMaker.getTestResultSummaryClass(), summaryId); if (summaryPo != null) { summaryPo.setMonitoringReport(null); summaryPo.setReportWritten(false); } } else { // Optimization: Since all monitoring reports need to be deleted, // we delete them with a JPQL query before removing // them via iteration. This prevents OutOfMemoryErrors // caused by loading all reports in to memory at the // same time. Query deleteMonitoringReportsQuery = session .createQuery("UPDATE " + PoMaker.getMonitoringReportClass().getSimpleName() //$NON-NLS-1$ + " SET report = null"); //$NON-NLS-1$ deleteMonitoringReportsQuery.executeUpdate(); session.flush(); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("SELECT summary FROM ") //$NON-NLS-1$ .append(PoMaker.getTestResultSummaryClass().getSimpleName()) .append(" AS summary where summary.reportWritten = :isReportWritten"); //$NON-NLS-1$ Query q = session.createQuery(queryBuilder.toString()); q.setParameter("isReportWritten", true); //$NON-NLS-1$ @SuppressWarnings("unchecked") List<ITestResultSummaryPO> reportList = q.getResultList(); for (ITestResultSummaryPO summary : reportList) { summary.setMonitoringReport(null); summary.setReportWritten(false); } } }
From source file:fr.mby.opa.picsimpl.dao.DbPictureDao.java
@Override public Picture updatePicture(final Picture picture) throws PictureNotFoundException { Assert.notNull(picture, "No Picture supplied !"); Assert.notNull(picture.getId(), "Id should be set for update !"); final TxCallbackReturn<Picture> txCallback = new TxCallbackReturn<Picture>(this.getEmf()) { @Override// w w w . j a va2 s.co m protected Picture executeInTransaction(final EntityManager em) { final Picture updatedPicture = em.merge(picture); em.flush(); em.refresh(updatedPicture); return updatedPicture; } }; final Picture updatedPicture = txCallback.getReturnedValue(); return updatedPicture; }
From source file:com.emc.plants.service.impl.LoginBean.java
/** * Create a new user./*from w w w .j a v a 2 s.co m*/ * * @param customerID The new customer ID. * @param password The password for the customer ID. * @param firstName First name. * @param lastName Last name. * @param addr1 Address line 1. * @param addr2 Address line 2. * @param addrCity City address information. * @param addrState State address information. * @param addrZip Zip code address information. * @param phone User's phone number. * @return CustomerInfo */ //@Transactional public CustomerInfo createNewUser(String customerID, String password, String firstName, String lastName, String addr1, String addr2, String addrCity, String addrState, String addrZip, String phone) { CustomerInfo customerInfo = null; /* customerHome = (CustomerHome) Util.getEJBLocalHome("java:comp/env/ejb/Customer", com.ibm.websphere.samples.pbwjpa.CustomerHome.class); try { // Only create new user if it doesn't already exist. customerHome.findByPrimaryKeyUpdate(customerID); } catch (ObjectNotFoundException onfe) { // Create customer and return true if all goes well. Customer customer = customerHome.create(new CustomerKey(customerID), password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); if (customer != null) customerInfo = new CustomerInfo(customer); } } catch (FinderException e) { e.printStackTrace(); } catch (CreateException e) { e.printStackTrace(); } */ Customer c = new Customer(customerID, password, firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone); EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); em.persist(c); em.flush(); em.getTransaction().commit(); customerInfo = new CustomerInfo(c); return customerInfo; }
From source file:com.edugility.substantia.substance.TestCasePerson.java
@Test public void testingJPA() throws Exception { final EntityManagerFactory emf = Persistence.createEntityManagerFactory("test"); assertNotNull(emf);/*from www. j a va2 s .c o m*/ final EntityManager em = emf.createEntityManager(); assertNotNull(em); final EntityTransaction et = em.getTransaction(); assertNotNull(et); et.begin(); final Person p = new Person(); em.persist(p); em.flush(); assertFalse(p.isTransient()); assertTrue(p.isVersioned()); assertEquals(Long.valueOf(1L), p.getId()); assertEquals(Integer.valueOf(1), p.getVersion()); et.commit(); et.begin(); final Person p2 = em.find(Person.class, 1L, LockModeType.OPTIMISTIC_FORCE_INCREMENT); assertNotNull(p2); assertFalse(p2.isTransient()); assertTrue(p2.isVersioned()); assertEquals(Long.valueOf(1L), p2.getId()); assertEquals(Integer.valueOf(1), p2.getVersion()); et.commit(); et.begin(); final Person p3 = em.getReference(Person.class, 1L); assertNotNull(p3); assertFalse(p3.isTransient()); assertTrue(p3.isVersioned()); assertEquals(Long.valueOf(1L), p3.getId()); assertEquals(Integer.valueOf(2), p3.getVersion()); et.commit(); et.begin(); assertTrue(em.contains(p)); em.remove(p); et.commit(); em.close(); emf.close(); }
From source file:org.springframework.batch.item.database.JpaItemWriter.java
/** * Merge all provided items that aren't already in the persistence context * and then flush the entity manager.//w w w.j a v a 2 s . c om * * @see org.springframework.batch.item.ItemWriter#write(java.util.List) */ @Override public void write(List<? extends T> items) { EntityManager entityManager = EntityManagerFactoryUtils.getTransactionalEntityManager(entityManagerFactory); if (entityManager == null) { throw new DataAccessResourceFailureException("Unable to obtain a transactional EntityManager"); } doWrite(entityManager, items); entityManager.flush(); }
From source file:org.unitils.orm.jpa.JpaModule.java
protected void flushOrmPersistenceContext(EntityManager activeEntityManager) { logger.info("Flushing entity manager " + activeEntityManager); activeEntityManager.flush(); }