Example usage for javax.persistence EntityManager clear

List of usage examples for javax.persistence EntityManager clear

Introduction

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

Prototype

public void clear();

Source Link

Document

Clear the persistence context, causing all managed entities to become detached.

Usage

From source file:org.droolsjbpm.services.test.ci.SessionMGMTandCIBaseTest.java

protected void completeOperation(UserTransaction ut, EntityManager entityManager) {
    if (ut != null) {
        try {// w w  w .  j a  v a 2  s  .com
            ut.commit();
            if (entityManager != null) {
                entityManager.clear();
                entityManager.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a busca de todos os usurios existentes no banco de dados.
 * @author Richel Sensineli/*from w  ww . j av a 2  s. co  m*/
 * @param nome String - Nome do usurio
 * @return Collection list
 */
@Override
public Collection buscaTodosUsuarios() {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();
    Query q = em.createQuery("select u from UsuarioImpl u");
    Collection result = null;
    result = q.getResultList();
    em.clear();
    em.close();
    emf.close();
    return result;
}

From source file:org.nuxeo.ecm.core.persistence.PersistenceProvider.java

protected void releaseEntityManager(EntityManager em) {
    if (!em.isOpen()) {
        return;//from  w w  w . ja va 2 s.co  m
    }
    try {
        doCommit(em);
    } finally {
        if (em.isOpen()) {
            em.clear();
            em.close();
        }
    }
}

From source file:org.nuxeo.ecm.core.persistence.PersistenceProvider.java

public void releaseEntityManagerWithRollback(EntityManager em) {
    if (!em.isOpen()) {
        return;//www. j  a  v a 2 s . co  m
    }
    try {
        doRollback(em);
    } finally {
        if (em.isOpen()) {
            em.clear();
            em.close();
        }
    }
}

From source file:org.grails.datastore.mapping.jpa.JpaSession.java

public void clear() {
    jpaTemplate.execute(new JpaCallback<Void>() {
        public Void doInJpa(EntityManager em) throws PersistenceException {
            em.clear();
            return null;
        }//from w w  w.ja va 2 s . co m
    });
}

From source file:org.apache.ranger.audit.destination.DBAuditDestination.java

private void clearEntityManager() {
    try {//from w  w  w.  j  av a  2s.  c  o  m
        EntityManager em = getEntityManager();

        if (em != null) {
            em.clear();
        }
    } catch (Exception excp) {
        logger.warn("DBAuditDestination.clearEntityManager(): failed", excp);
    }
}

From source file:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para realizar a busca de usurio pelo ID.
 * @author Richel Sensineli//from   ww  w.  ja va 2  s . com
 * @param id int - ID do usurio
 * @return Usuario usuario - Objeto Usuario
 */
@Override
public Usuario buscaUsuarioPorId(final int id) throws UsuarioNaoEncontradoException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();
    Usuario u = em.find(UsuarioImpl.class, id);
    if (u == null) {
        throw new UsuarioNaoEncontradoException("usuario no encontrado");
    }
    em.clear();
    em.close();
    emf.close();
    return u;
}

From source file:org.apache.ranger.audit.provider.DbAuditProvider.java

private void clearEntityManager() {
    try {/* w  w w.ja v a  2  s . co m*/
        EntityManager em = getEntityManager();

        if (em != null) {
            em.clear();
        }
    } catch (Exception excp) {
        LOG.warn("DbAuditProvider.clearEntityManager(): failed", excp);
    }
}

From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testPersist() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager em = emf.createEntityManager();
    PObject pc = new PObject("XYZ");
    em.getTransaction().begin();/*ww w . ja  v  a2s  . c  om*/
    em.persist(pc);
    em.getTransaction().commit();
    Object oid = pc.getId();

    em.clear();
    // After clean the instance must not be in L1 cache
    assertFalse(em.contains(pc));
    // But it must be found in L2 cache by its OpenJPA identifier
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));

    PObject pc2 = em.find(PObject.class, oid);
    // After find(), the original instance is not in the L1 cache
    assertFalse(em.contains(pc));
    // After find(), the found instance is in the L1 cache
    assertTrue(em.contains(pc2));
    // The L2 cache must still hold the key   
    assertTrue(getCache(pc.getClass()).contains(getOpenJPAId(pc, oid)));
}

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;/*  www .java  2  s .  c o  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());
}