Example usage for javax.persistence EntityManager remove

List of usage examples for javax.persistence EntityManager remove

Introduction

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

Prototype

public void remove(Object entity);

Source Link

Document

Remove the entity instance.

Usage

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteInstalledBun(final InstalledBun message) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from w  w w .  ja v  a  2 s.  co m

    entityManager.remove(message);

    entityTransaction.commit();
}

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  w  w.ja v  a2s  .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());
}

From source file:commonSession.PersistAttivitaFacadeBean.java

public void delete(Object id, Class clazz, String unit) throws Exception {

    //    EntityManager em;
    EntityManager em = GestionaleEm;
    if (unit.equals("GestionaleEm"))
        em = GestionaleEm;/*from w  ww.  j av  a  2 s .  c o m*/
    else
        em = TerritorioEm;

    Object obj = em.find(clazz, id);
    em.remove(obj);
    em.flush();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteUser(int userid) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    BakerUser u = entityManager.find(BakerUser.class, userid);

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from w w  w.  j a v a 2  s.c o  m

    entityManager.remove(u);

    entityTransaction.commit();
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*www . j a v  a  2 s . c  o m*/
 */
@Override
public <T extends BaseEntity> void delete(Class<T> entity, Object primaryKey) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        T entityToDelete = em.find(entity, primaryKey);
        if (entityToDelete == null) {
            LOGGER.warn("Entity couldn't be deleted as it doesn't exists in DB: [{}]", entity);
        } else {
            em.remove(entityToDelete);
            em.getTransaction().commit();
        }
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteProperty(int propid) {

    EntityManager entityManager = entityManagerFactory.createEntityManager();
    BakerProperty c = entityManager.find(BakerProperty.class, propid);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*from www  .  jav a 2 s.c o m*/
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteSubscribedResource(int smId) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    SubscribedResource sm = entityManager.find(SubscribedResource.class, smId);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from w  ww  . ja  v a  2  s  .  co m
    entityManager.remove(sm);
    entityTransaction.commit();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteDeployment(int id) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    DeploymentDescriptor c = entityManager.find(DeploymentDescriptor.class, id);

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();/*from   w  w w . j a v a  2s  .  c  om*/
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:org.apache.juddi.api.impl.UDDICustodyTransferImpl.java

@SuppressWarnings("unchecked")
public void discardTransferToken(DiscardTransferToken body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  ww w  .  j  ava 2  s .  c om
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateCustodyTransfer(publisher).validateDiscardTransferToken(em, body);

        org.uddi.custody_v3.TransferToken apiTransferToken = body.getTransferToken();
        if (apiTransferToken != null) {
            String transferTokenId = new String(apiTransferToken.getOpaqueToken());
            org.apache.juddi.model.TransferToken modelTransferToken = em
                    .find(org.apache.juddi.model.TransferToken.class, transferTokenId);
            if (modelTransferToken != null)
                em.remove(modelTransferToken);
        }

        KeyBag keyBag = body.getKeyBag();
        if (keyBag != null) {
            List<String> keyList = keyBag.getKey();
            Vector<DynamicQuery.Parameter> params = new Vector<DynamicQuery.Parameter>(0);
            for (String key : keyList) {
                // Creating parameters for key-checking query
                DynamicQuery.Parameter param = new DynamicQuery.Parameter("UPPER(ttk.entityKey)",
                        key.toUpperCase(), DynamicQuery.PREDICATE_EQUALS);

                params.add(param);
            }

            // Find the associated transfer tokens and remove them.
            DynamicQuery getTokensQry = new DynamicQuery();
            getTokensQry.append("select distinct ttk.transferToken from TransferTokenKey ttk").pad();
            getTokensQry.WHERE().pad().appendGroupedOr(params.toArray(new DynamicQuery.Parameter[0]));

            Query qry = getTokensQry.buildJPAQuery(em);
            List<org.apache.juddi.model.TransferToken> tokensToDelete = qry.getResultList();
            if (tokensToDelete != null && tokensToDelete.size() > 0) {
                for (org.apache.juddi.model.TransferToken tt : tokensToDelete)
                    em.remove(tt);
            }
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(CustodyTransferQuery.DISCARD_TRANSFERTOKEN, QueryStatus.SUCCESS, procTime);

    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:nl.b3p.viewer.admin.stripes.AttributeSourceActionBean.java

public Resolution delete() {
    EntityManager em = Stripersist.getEntityManager();

    if (!featureSource.getFeatureTypes().isEmpty()) {
        em.createQuery("update Layer set featureType = null where featureType in :fts")
                .setParameter("fts", featureSource.getFeatureTypes()).executeUpdate();
        em.createQuery("update ConfiguredAttribute set featureType=null where featureType in :fts")
                .setParameter("fts", featureSource.getFeatureTypes()).executeUpdate();
    }/*from  w w w . j a  v  a2s  .  c om*/

    em.remove(featureSource);

    Stripersist.getEntityManager().getTransaction().commit();

    getContext().getMessages().add(new SimpleMessage("Attribuutbron is verwijderd"));
    return new ForwardResolution(EDITJSP);
}