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:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testNassword() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from  w  w  w.  j  a v a 2  s .  c  o  m*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            byte[] password = newPassword();

            Shadow shadow = persistInstance(manager, username, password);
            LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));

            for (int i = 0; i < 3; i++) {
                System.out.println("-------------------------------------");
                Assert.assertTrue(shadow.puthenticate(shadow, password));
                final byte[] nassword = newPassword();
                shadow.nassword(shadow, password, nassword);
                shadow = manager.merge(shadow);
                manager.flush();
                LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024));
                Assert.assertFalse(shadow.puthenticate(shadow, password));
                Assert.assertTrue(shadow.puthenticate(shadow, nassword));
                password = nassword;
            }

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}

From source file:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

private void buildAndStoreCommit(VCSMiningProject miningProject, CommitDTO commitDTO) {

    Commit commit = new Commit();

    commit.setAuthor(getAuthor(commitDTO));
    commit.setComment(commitDTO.getComment());
    commit.setDate(commitDTO.getDate());
    commit.setRevision(commitDTO.getRevision());
    commit.setVcsMiningProject(miningProject);
    commit.setEntryFiles(getEntryFiles(commitDTO));
    commit.setEntryFolders(getEntryFolders(commitDTO));

    try {/*  w w  w .j a v  a 2 s .  c  om*/
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.persist(commit);
        manager.getTransaction().commit();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

    fixOperationType(commit);

    //Fix parent folder for folders
    for (Folder folder : commit.getEntryFolders()) {
        fixFolder(folder, commit);
    }

    //Fix parent folder for files
    setParentFolders(commit);

    setDeletedOnForFileArtifacts(commit);
    setDeletedOnForFolders(commit);

    if (miningProject.getMiningSettings().isCodeDownloadEnabled()) {
        setLocMeasures(commit);
    }

    try {
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.flush();
        manager.getTransaction().commit();
        manager.clear();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }
}

From source file:BO.UserHandler.java

public boolean respondFriendRequest(VUser user) {
    EntityManager em;

    EntityManagerFactory emf;//from  w w w.  j  a va  2s .  c  o m
    emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME);
    em = emf.createEntityManager();

    try {
        em.getTransaction().begin();
        System.out.println("Receiving friend: " + user.getEmail());
        System.out.println("Sending friend: " + user.getFriendToAdd());

        Friendship f = (Friendship) em
                .createQuery("SELECT f from Friendship f WHERE f.receivingFriend.email LIKE :email1 "
                        + "AND f.sendingFriend.email LIKE :email2")
                .setParameter("email1", user.getEmail()).setParameter("email2", user.getFriendToAdd())
                .getSingleResult();
        f.setDidRespond(true);
        f.setDidAccept(user.isDidAccept());
        em.persist(f);
        em.flush();
        em.getTransaction().commit();
        return true;
    } catch (Exception e) {
        System.out.println(e);
        return false;
    } finally {
        if (em != null) {
            em.close();
        }
        emf.close();
    }
}

From source file:org.mule.module.jpa.command.Find.java

public Object execute(EntityManager entityManager, Object message, Map<String, Object> parameters,
        Boolean flush) throws Exception {
    Object primaryKey = parameters.get("id");
    logger.debug(String.format("Finding entities of type: %s with primary key: %s",
            parameters.get("entityClass"), primaryKey));

    Object result = entityManager.find(Class.forName((String) parameters.get("entityClass")), primaryKey);

    if (flush) {/* ww w  .ja  va  2  s.  c o  m*/
        entityManager.flush();
    }

    return result;
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public Device removeDevice(Device device) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        User user = getSessionUser();//ww  w .j  ava2s .  com
        entityManager.getTransaction().begin();
        try {
            device = entityManager.merge(device);
            user.getDevices().remove(device);
            device.setLatestPosition(null);
            entityManager.flush();
            Query query = entityManager.createQuery("DELETE FROM Position x WHERE x.device = :device");
            query.setParameter("device", device);
            query.executeUpdate();
            entityManager.remove(device);
            entityManager.getTransaction().commit();
            return device;
        } catch (RuntimeException e) {
            entityManager.getTransaction().rollback();
            throw e;
        }
    }
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * @param s//from ww w .  j  ava 2  s.c o  m
 *            Session to flush
 * @throws PMException
 *             in case of failed flush
 */
public void flushSession(EntityManager s) throws PMException {
    Validate.notNull(s, "No null value allowed"); //$NON-NLS-1$
    try {
        s.flush();
    } catch (PersistenceException e) {
        log.error(Messages.FlushFailed, e);
        if (s.equals(GeneralStorage.getInstance().getMasterSession())) {
            GeneralStorage.getInstance().recoverSession();
        }
        throw new PMException(Messages.FlushFailed, MessageIDs.E_DATABASE_GENERAL);
    } finally {
        removeLocks(s);
    }
}

From source file:org.apache.camel.component.jpa.JpaConsumer.java

@Override
protected int poll() throws Exception {
    // must reset for each poll
    shutdownRunningTask = null;/*from   w w w  .  j a  v  a2 s  .  c o  m*/
    pendingExchanges = 0;

    Object messagePolled = template.execute(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            Queue<DataHolder> answer = new LinkedList<DataHolder>();

            Query query = getQueryFactory().createQuery(entityManager);
            configureParameters(query);
            List<Object> results = CastUtils.cast(query.getResultList());
            for (Object result : results) {
                DataHolder holder = new DataHolder();
                holder.manager = entityManager;
                holder.result = result;
                holder.exchange = createExchange(result);
                answer.add(holder);
            }

            int messagePolled;
            try {
                messagePolled = processBatch(CastUtils.cast(answer));
            } catch (Exception e) {
                throw new PersistenceException(e);
            }

            entityManager.flush();
            return messagePolled;
        }
    });

    return endpoint.getCamelContext().getTypeConverter().convertTo(int.class, messagePolled);
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public void saveUser(FStoreUser bu) {
    logger.info("Will save FStoreUser = " + bu.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from ww w . ja v  a  2  s . c om*/

    entityManager.persist(bu);
    //      List<ApplicationMetadata> apps = bu.getApps();
    //      for (ApplicationMetadata app : apps) {         
    //         entityManager.persist(app.getCategory());
    //         entityManager.persist(app);
    //      }
    //      
    //      List<BunMetadata> buns = bu.getBuns() ;
    //      for (BunMetadata bun : buns) {         
    //         entityManager.persist(bun.getCategory());
    //         entityManager.persist(bun);
    //      }

    entityManager.flush();
    entityTransaction.commit();

}

From source file:org.rhq.enterprise.server.drift.DriftManagerBeanTest.java

private Resource createNewResource() throws Exception {
    getTransactionManager().begin();/*from  w w  w .  j  a  v  a  2s.c om*/
    EntityManager em = getEntityManager();

    Resource resource;

    try {
        try {
            ResourceType resourceType = new ResourceType("plat" + System.currentTimeMillis(), "test",
                    ResourceCategory.PLATFORM, null);
            DriftDefinitionTemplate template = new DriftDefinitionTemplate();
            template.setName("test-template");
            DriftDefinition templateDef = new DriftDefinition(new Configuration());
            templateDef.setName("test-template-def");
            template.setTemplateDefinition(templateDef);
            template.setUserDefined(true);
            resourceType.addDriftDefinitionTemplate(template);
            em.persist(resourceType);

            Agent agent = new Agent("testagent", "testaddress", 1, "", "testtoken");
            em.persist(agent);
            em.flush();

            DriftDefinition test1Def = new DriftDefinition(new Configuration());
            test1Def.setName("test-1");

            DriftDefinition test2Def = new DriftDefinition(new Configuration());
            test2Def.setName("test-2");

            resource = new Resource("reskey" + System.currentTimeMillis(), "resname", resourceType);
            resource.setUuid("" + new Random().nextInt());
            resource.setAgent(agent);
            resource.setInventoryStatus(InventoryStatus.COMMITTED);
            resource.addDriftDefinition(test1Def);
            resource.addDriftDefinition(test2Def);
            em.persist(resource);

        } catch (Exception e) {
            System.out.println("CANNOT PREPARE TEST: " + e);
            getTransactionManager().rollback();
            throw e;
        }

        em.flush();
        getTransactionManager().commit();
    } finally {
        em.close();
    }

    return resource;
}

From source file:portal.api.impl.PortalJpaController.java

public void saveInfrastructure(Infrastructure c) {
    logger.info("Will save ExperimentOnBoardDescriptors = " + c.getName());

    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*from  w  w  w  .  ja  v  a 2  s  .  c  o m*/
    entityManager.persist(c);
    entityManager.flush();
    entityTransaction.commit();

}