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:eu.forgestore.ws.impl.FStoreJpaController.java

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

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//ww  w  .j  a  va 2 s  . c o  m

    entityManager.remove(u);

    entityTransaction.commit();
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *///from   w w  w.java  2s  .  c om
public void cleanup(UXBEntity entity) throws Exception {

    EntityManager em = null;
    EntityTransaction tx = null;
    try {

        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();

        Query query = em.createQuery(new StringBuilder()
                .append("SELECT x FROM article x WHERE x.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                em.remove(art);
            }
        }
        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while deleting from the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }

}

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

public void deleteProperty(int propid) {

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

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from ww w.  j a v  a2 s .  c o m
    entityManager.remove(c);
    entityTransaction.commit();

}

From source file:org.rhq.enterprise.server.resource.test.ResourceFactoryManagerBeanTest.java

/**
 * Deletes a previously persisted resource from the database.
 *
 * @throws Exception if anything goes wrong
 *///from  ww w  .j  a v a 2s  .c  o m
private void teardownResourceEnvironment() throws Exception {
    if (parentResource != null) {

        List<Integer> deletedIds = resourceManager.uninventoryResource(overlord, parentResource.getId());
        for (Integer deletedResourceId : deletedIds) {
            resourceManager.uninventoryResourceAsyncWork(overlord, deletedResourceId);
        }

        getTransactionManager().begin();
        EntityManager em = getEntityManager();
        try {
            // Remove the child first.
            ResourceType deleteMeType = em.find(ResourceType.class, childResourceType.getId());
            em.remove(deleteMeType);

            deleteMeType = em.find(ResourceType.class, parentResourceType.getId());
            em.remove(deleteMeType);

            getTransactionManager().commit();
        } catch (Exception e) {
            try {
                System.out.println(e);
                getTransactionManager().rollback();
            } catch (Exception ignore) {
            }

            throw e;
        } finally {
            em.close();
        }
    }
}

From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

@Override
public void deleteComment(String eventId, long commentId)
        throws NotFoundException, EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {/*from   w  w w  .  ja va  2  s  . c om*/
        tx.begin();
        EventCommentDto event = getEventComment(eventId, commentId, em);
        if (event == null)
            throw new NotFoundException(
                    "Event comment with ID " + eventId + " and " + commentId + " does not exist");

        em.remove(event);
        tx.commit();
        sendMessageUpdate(eventId);
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete event comment: {}", ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();

        throw new EventCommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:edu.vt.middleware.gator.JpaConfigManager.java

/** {@inheritDoc}. */
@Transactional(propagation = Propagation.REQUIRED)
public void delete(final ProjectConfig project) {
    final EntityManager em = getEntityManager();
    if (logger.isDebugEnabled()) {
        logger.debug("Deleting " + project);
    }//from   w ww .j av  a 2  s  . com

    ProjectConfig liveProject = project;
    if (!em.contains(project)) {
        liveProject = find(ProjectConfig.class, project.getId());
    }
    // Touch all collections to lazy load dependent data so complete project
    // configuration is available to event handlers
    liveProject.getAppenders();
    liveProject.getCategories();
    liveProject.getClients();
    liveProject.getPermissions();

    em.remove(liveProject);

    // Fire events on a separate thread so we do not disrupt client thread
    // (e.g. avoid subscriber blocking)
    for (ConfigChangeListener listener : getConfigChangeListeners()) {
        eventExecutor.execute(new ProjectRemovedEvent(listener, liveProject));
    }
}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

@Override
public void deleteOntology(final String uuid) throws ArtificerException {
    new HibernateUtil.HibernateTask<Void>() {
        @Override/*from  www .j  a v  a 2 s  . c om*/
        protected Void doExecute(EntityManager entityManager) throws Exception {
            ArtificerOntology ontology = HibernateUtil.getOntology(uuid, entityManager);
            HibernateUtil.evict(ArtificerOntology.class, ontology.getSurrogateId(), entityManager);
            // Orphan removal is not honored by JPQL, so we need to manually delete using #remove.
            entityManager.remove(ontology);
            return null;
        }
    }.execute();
}

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

private void setOperationalInfo(EntityManager em, org.apache.juddi.model.Tmodel uddiEntity,
        UddiEntityPublisher publisher) throws DispositionReportFaultMessage {

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);/*  ww  w .j av  a  2 s .c o m*/
    uddiEntity.setModifiedIncludingChildren(now);

    uddiEntity.setNodeId(nodeId);

    org.apache.juddi.model.Tmodel existingUddiEntity = em.find(uddiEntity.getClass(),
            uddiEntity.getEntityKey());
    if (existingUddiEntity != null)
        uddiEntity.setCreated(existingUddiEntity.getCreated());
    else
        uddiEntity.setCreated(now);

    if (existingUddiEntity != null)
        em.remove(existingUddiEntity);

}

From source file:org.artificer.repository.hibernate.HibernatePersistenceManager.java

@Override
public void deleteStoredQuery(final String queryName) throws ArtificerException {
    new HibernateUtil.HibernateTask<Void>() {
        @Override/*from w ww  .jav a  2  s.c o  m*/
        protected Void doExecute(EntityManager entityManager) throws Exception {
            // Orphan removal is not honored by JPQL, so we need to manually delete using #remove.
            ArtificerStoredQuery storedQuery = entityManager.find(ArtificerStoredQuery.class, queryName);
            if (storedQuery == null) {
                throw ArtificerNotFoundException.storedQueryNotFound(queryName);
            }

            entityManager.remove(storedQuery);
            HibernateUtil.evict(ArtificerStoredQuery.class, storedQuery.getQueryName(), entityManager);

            return null;
        }
    }.execute();
}

From source file:org.rhq.enterprise.server.content.test.RepoManagerBeanTest.java

@Test(enabled = ENABLED)
public void getRepoGroupTypeByName() throws Exception {
    // Setup/*w  w w . j  av a 2s .  c  o m*/
    EntityManager entityManager = getEntityManager();
    String name = "test-repo-type";

    RepoGroupType groupType = new RepoGroupType(name);
    entityManager.persist(groupType);
    entityManager.flush();

    // Test
    RepoGroupType type = repoManager.getRepoGroupTypeByName(overlord, name);
    assert type != null;
    assert type.getName().equals(name);

    // Cleanup
    type = entityManager.find(RepoGroupType.class, type.getId());
    entityManager.remove(type);
    entityManager.flush();
}