Example usage for javax.persistence EntityManager flush

List of usage examples for javax.persistence EntityManager flush

Introduction

In this page you can find the example usage for javax.persistence EntityManager flush.

Prototype

public void flush();

Source Link

Document

Synchronize the persistence context to the underlying database.

Usage

From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testLifeCycleLoadFlushModifyFlush() {
    insert(newLobEntity(createLobData(), 1));
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//from  w w w .ja  v  a2s  .  c o m
    LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1);
    em.flush();
    changeStream(entity, createLobData2());
    em.flush();
    em.getTransaction().commit();
    em.close();
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployeeRepositoryImplementation.java

@Override
public boolean update(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {//from   ww w . j  a  v a2  s .c o  m
        em.getTransaction().begin();

        em.merge(employee);
        em.flush();

        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:org.opennaas.core.security.acl.ACLManager.java

private void executeSqlQuery(String sqlQuery) {
    log.debug("Executing SQL query: [ " + sqlQuery + " ]");
    EntityManager em = securityRepository.getEntityManager();
    EntityTransaction et = em.getTransaction();
    et.begin();/*from   w  ww  .j a  v a  2 s. c o  m*/
    try {
        em.createNativeQuery(sqlQuery).executeUpdate();
        em.flush();
        et.commit();
        log.debug("SQL query executed.");
    } catch (Exception e) {
        log.error("Error executing SQL query, rollbacking", e);
        et.rollback();
    }
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

/**
 * @param proposalBag//from  www.ja  va  2 s. c o m
 * @return
 */
protected ProposalBag _updateProposalBagInternal(final ProposalBag proposalBag) {
    final TxCallbackReturn<ProposalBag> txCallback = new TxCallbackReturn<ProposalBag>(this.getEmf()) {

        @Override
        protected ProposalBag executeInTransaction(final EntityManager em) {
            final ProposalBag updatedBag = em.merge(proposalBag);
            em.flush();
            em.refresh(updatedBag);
            return updatedBag;
        }
    };

    final ProposalBag updatedBag = txCallback.getReturnedValue();
    return updatedBag;
}

From source file:com.doculibre.constellio.services.ImportExportServicesImpl.java

@Override
public void importData(Workbook workbook, RecordCollection collection, ProgressInfo progressInfo) {
    ConnectorInstance connectorInstance = collection.getConnectorInstances().iterator().next();
    RecordServices recordServices = ConstellioSpringUtils.getRecordServices();
    Sheet sheet = workbook.getSheet(0);//from  w  w w.  j a v  a 2  s . co m

    if (progressInfo != null) {
        progressInfo.setTotal(sheet.getRows());
    }

    List<String> metaNames = new ArrayList<String>();
    for (int column = 0; column < sheet.getColumns(); column++) {
        Cell cell = sheet.getCell(column, 0);
        String metaName = cell.getContents();
        metaNames.add(metaName);
    }

    for (int row = 1; row < sheet.getRows(); row++) {
        Record record = new Record();
        record.setConnectorInstance(connectorInstance);
        for (int column = 0; column < sheet.getColumns(); column++) {
            Cell cell = sheet.getCell(column, row);
            RecordMeta meta = new RecordMeta();
            meta.setRecord(record);
            record.getContentMetas().add(meta);
            String metaName = metaNames.get(column);
            String metaContent = cell.getContents();
            ConnectorInstanceMeta connectorInstanceMeta = connectorInstance.getOrCreateMeta(metaName);
            meta.setConnectorInstanceMeta(connectorInstanceMeta);
            meta.setContent(metaContent);
        }

        Record existingRecord = recordServices.get(record.getUrl(), connectorInstance.getRecordCollection());
        if (existingRecord == null) {
            recordServices.makePersistent(record);
        }
        EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
        entityManager.flush();

        if (progressInfo != null) {
            progressInfo.setCurrentIndex(row - 1);
        }
    }
}

From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testLifeCycleInsertFlushModify() {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//from  w ww .j  av a  2 s  .co m
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    em.flush();
    changeStream(le, createLobData2());
    em.getTransaction().commit();
    em.close();
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBranch updateBranch(final ProposalBranch branch) {
    Assert.notNull(branch, "No ProposalBag supplied !");
    Assert.notNull(branch.getId(), "Id should be set for update !");

    final TxCallbackReturn<ProposalBranch> txCallback = new TxCallbackReturn<ProposalBranch>(this.getEmf()) {

        @Override//from w w w .j  ava2  s .  c o  m
        protected ProposalBranch executeInTransaction(final EntityManager em) {
            final ProposalBranch updatedBranch = em.merge(branch);
            em.flush();
            em.refresh(updatedBranch);
            return updatedBranch;
        }
    };

    final ProposalBranch updatedBag = txCallback.getReturnedValue();
    return updatedBag;
}

From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testSetFlushAndReset() throws IOException {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//  w  ww  .  j  av a2  s.  com
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    em.flush();
    String string = createLobData2();
    changeStream(le, string);
    LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1);
    assertEquals(string, getStreamContentAsString(entity.getStream()));
    em.getTransaction().commit();
    em.close();
}

From source file:com.chiralbehaviors.CoRE.access.resource.CollectionResource.java

@POST
@Path("{parentId}")
@Produces(MediaType.APPLICATION_JSON)//from w w w.j  a  v  a 2 s.c  o m
public Product createNewProduct(@PathParam("parentId") String parentId, @QueryParam("relId") String relId,
        Product child) throws JsonProcessingException {
    return perform(new Transactionally<Product>() {

        @Override
        public Product exec(Model model) throws SQLException {
            EntityManager em = model.getEntityManager();
            Product parent = em.find(Product.class, parentId);
            Relationship rel = em.find(Relationship.class, relId);
            em.persist(child);
            ProductNetwork net = new ProductNetwork(parent, rel, child, parent.getUpdatedBy());
            em.persist(net);
            em.flush();
            em.refresh(child);
            return child;
        }
    });
}

From source file:com.openmeap.model.ModelTestUtils.java

static public void createModel(EntityManager em) {
    if (em == null) {
        em = createEntityManager();//from  w  w w  .j av  a2 s  .  c o m
    }
    try {
        Map<String, Map<String, ? extends ModelEntity>> modelBeans = (Map<String, Map<String, ? extends ModelEntity>>) ModelTestUtils
                .newModelBeans().getBean("mockModel");

        // we need to set all (except the Device.uuid) pk's to null,
        // so the entity manager doesn't flip out, thinking we've passed it
        // a detached entity for persistence.
        for (Map.Entry<String, Map<String, ? extends ModelEntity>> classes : modelBeans.entrySet())
            for (ModelEntity member : classes.getValue().values())
                if (!(member instanceof ApplicationInstallation))
                    member.setPk(null);

        em.getTransaction().begin();

        for (String className : new String[] { "GlobalSettings", "Application", "ApplicationArchive",
                "ApplicationVersion", "Deployment", "ApplicationInstallation" }) {
            Map<String, ? extends ModelEntity> members = modelBeans.get(className);
            for (ModelEntity member : members.values()) {
                if (className.equals("Application")) {
                    ((Application) member).setDeployments(null);
                }
                em.persist(member);
                em.flush();
            }
        }

        em.getTransaction().commit();

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}