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:org.traccar.web.server.model.DataServiceImpl.java

@Override
public Device removeDevice(Device device) {
    EntityManager entityManager = getSessionEntityManager();
    synchronized (entityManager) {
        User user = getSessionUser();/*  w ww . ja  va  2s. 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.rhq.enterprise.server.content.test.RepoManagerBeanTest.java

@Test(enabled = ENABLED)
public void createDuplicateRepoGroup() throws Exception {
    // Setup/*from  w  w  w  . j  av  a  2  s .c  o m*/
    EntityManager entityManager = getEntityManager();

    RepoGroupType groupType = new RepoGroupType("testCreateDuplicateRepoGroup");
    entityManager.persist(groupType);
    entityManager.flush();

    String groupName = "testCreateDuplicateRepoGroup";

    RepoGroup existing = new RepoGroup(groupName);
    existing.setRepoGroupType(groupType);
    repoManager.createRepoGroup(overlord, existing);

    existing = repoManager.getRepoGroupByName(groupName);
    assert existing != null;

    // Test
    RepoGroup duplicate = new RepoGroup(groupName);
    duplicate.setRepoGroupType(groupType);

    try {
        repoManager.createRepoGroup(overlord, existing);
        assert false;
    } catch (RepoException e) {
        // Expected
    }

    // Cleanup
    repoManager.deleteRepoGroup(overlord, existing.getId());
    existing = repoManager.getRepoGroup(overlord, existing.getId());
    assert existing == null;

    entityManager.remove(groupType);
}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@Override
public void deleteSeries(String seriesId) throws SeriesServiceDatabaseException, NotFoundException {
    EntityManager em = emf.createEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {// ww w . j a v  a2 s.  c o  m
        tx.begin();
        SeriesEntity entity = getSeriesEntity(seriesId, em);
        if (entity == null) {
            throw new NotFoundException("Series with ID " + seriesId + " does not exist");
        }
        // Ensure this user is allowed to delete this series
        String accessControlXml = entity.getAccessControl();
        if (accessControlXml != null) {
            AccessControlList acl = AccessControlParser.parseAcl(accessControlXml);
            User currentUser = securityService.getUser();
            Organization currentOrg = securityService.getOrganization();
            if (!AccessControlUtil.isAuthorized(acl, currentUser, currentOrg, EDIT_SERIES_PERMISSION)) {
                throw new UnauthorizedException(
                        currentUser + " is not authorized to update series " + seriesId);
            }
        }
        em.remove(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete series: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}

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

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

    uddiEntity.setAuthorizedName(publisher.getAuthorizedName());

    Date now = new Date();
    uddiEntity.setModified(now);//from   w w  w . ja v a  2  s. c om
    uddiEntity.setModifiedIncludingChildren(now);

    if (!isChild) {
        org.apache.juddi.model.BusinessEntity parent = em.find(org.apache.juddi.model.BusinessEntity.class,
                uddiEntity.getBusinessEntity().getEntityKey());
        parent.setModifiedIncludingChildren(now);
        em.persist(parent);
    }

    uddiEntity.setNodeId(nodeId);

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

    List<org.apache.juddi.model.BindingTemplate> bindingList = uddiEntity.getBindingTemplates();
    for (org.apache.juddi.model.BindingTemplate binding : bindingList)
        setOperationalInfo(em, binding, publisher, true);

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

}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.BaseJpaDaoTest.java

/**
 * Deletes ALL entities from the database
 *//*from w ww  .j a v  a2s.  c  o  m*/
@After
public final void deleteAllEntities() {
    final EntityManager entityManager = getEntityManager();
    final EntityManagerFactory entityManagerFactory = entityManager.getEntityManagerFactory();
    final Metamodel metamodel = entityManagerFactory.getMetamodel();
    Set<EntityType<?>> entityTypes = new LinkedHashSet<EntityType<?>>(metamodel.getEntities());

    do {
        final Set<EntityType<?>> failedEntitieTypes = new HashSet<EntityType<?>>();

        for (final EntityType<?> entityType : entityTypes) {
            final String entityClassName = entityType.getBindableJavaType().getName();

            try {
                this.executeInTransaction(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        logger.trace("Purging all: " + entityClassName);

                        final Query query = entityManager
                                .createQuery("SELECT e FROM " + entityClassName + " AS e");
                        final List<?> entities = query.getResultList();
                        logger.trace("Found " + entities.size() + " " + entityClassName + " to delete");
                        for (final Object entity : entities) {
                            entityManager.remove(entity);
                        }

                        return null;
                    }
                });
            } catch (DataIntegrityViolationException e) {
                logger.trace(
                        "Failed to delete " + entityClassName + ". Must be a dependency of another entity");
                failedEntitieTypes.add(entityType);
            }
        }

        entityTypes = failedEntitieTypes;
    } while (!entityTypes.isEmpty());

    //Reset all spring managed mocks after every test
    MockitoFactoryBean.resetAllMocks();
}

From source file:com.jada.admin.site.SiteLoader.java

public void remove() throws Exception {
    EntityManager em = JpaConnection.getInstance().getCurrentEntityManager();
    String sql = null;// ww w  .  j a va2s.  c  om
    Query query = null;
    Iterator<?> iterator = null;

    sql = "delete from CreditCard where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "from Report report where report.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Report report = (Report) iterator.next();
        em.remove(report);
    }

    sql = "from IeProfileHeader ieProfileHeader where ieProfileHeader.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        IeProfileHeader ieProfileHeader = (IeProfileHeader) iterator.next();
        for (IeProfileDetail ieProfileDetail : ieProfileHeader.getIeProfileDetails()) {
            em.remove(ieProfileDetail);
        }
        em.remove(ieProfileHeader);
    }

    sql = "from Menu menu where menu.siteDomain in (select siteDomain from SiteDomain siteDomain where siteDomain.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Menu menu = (Menu) iterator.next();
        menu.setMenuLanguage(null);
        for (MenuLanguage menuLanguage : menu.getMenuLanguages()) {
            em.remove(menuLanguage);
        }
        em.remove(menu);
    }

    sql = "from Category category where category.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Category category = (Category) iterator.next();
        category.setCategoryLanguage(null);
        for (CategoryLanguage categoryLanguage : category.getCategoryLanguages()) {
            em.remove(categoryLanguage);
        }
        em.remove(category);
    }

    sql = "delete from ProductClass productClass where productClass.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "delete from CustomerClass customerClass where customerClass.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    query.executeUpdate();

    sql = "from ShippingRate shippingRate " + "where   shippingRate in ( " + "select   shippingRate "
            + "from      ShippingMethodRegionType shippingMethodRegionType "
            + "where   shippingMethodRegionType.shippingMethod.site.siteId = :siteId " + ")";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRate shippingRate = (ShippingRate) iterator.next();
        em.remove(shippingRate);
    }

    sql = "from ShippingMethod where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingMethod shippingMethod = (ShippingMethod) iterator.next();
        em.remove(shippingMethod.getShippingMethodLanguage());
        em.remove(shippingMethod);
    }

    sql = "from ShippingRegion where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingRegion shippingRegion = (ShippingRegion) iterator.next();
        em.remove(shippingRegion);
    }

    sql = "from ShippingType where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        ShippingType shippingType = (ShippingType) iterator.next();
        em.remove(shippingType);
    }

    sql = "from State where stateId in (select stateId from State state where state.country.site.siteId = :siteId)";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        State state = (State) iterator.next();
        state.setCountry(null);
        em.remove(state);
    }

    sql = "from Country where siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Country country = (Country) iterator.next();
        em.remove(country);
    }
    site.setSiteCurrencyClassDefault(null);
    site.setSiteProfileClassDefault(null);

    for (SiteDomain siteDomain : site.getSiteDomains()) {
        siteDomain.setSiteProfileDefault(null);
        siteDomain.setSiteCurrencyDefault(null);
        siteDomain.setBaseCurrency(null);
        siteDomain.setSiteDomainLanguage(null);

        HomePage homePage = siteDomain.getHomePage();
        for (HomePageDetail homePageDetail : homePage.getHomePageDetails()) {
            em.remove(homePageDetail);
        }
        for (HomePageLanguage homePageLanguage : homePage.getHomePageLanguages()) {
            em.remove(homePageLanguage);
        }
        em.remove(homePage);
        siteDomain.setHomePage(null);

        Template template = siteDomain.getTemplate();
        em.remove(template);
        siteDomain.setTemplate(null);
    }

    sql = "from SiteProfile siteProfile where siteProfile.siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfile siteProfile = (SiteProfile) iterator.next();
        em.remove(siteProfile);
    }

    sql = "from SiteCurrency siteCurrency where siteCurrency.siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrency siteCurrency = (SiteCurrency) iterator.next();
        em.remove(siteCurrency);
    }

    sql = "from SiteProfileClass siteProfileClass where siteProfileClass.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteProfileClass siteProfileClass = (SiteProfileClass) iterator.next();
        em.remove(siteProfileClass);
    }

    sql = "from SiteCurrencyClass siteCurrencyClass where siteCurrencyClass.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteCurrencyClass siteCurrencyClass = (SiteCurrencyClass) iterator.next();
        siteCurrencyClass.setCurrency(null);
        em.remove(siteCurrencyClass);
    }

    sql = "from Currency currency where currency.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        Currency currency = (Currency) iterator.next();
        em.remove(currency);
    }

    sql = "from CustomAttribute customAttribute where customAttribute.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        CustomAttribute customAttribute = (CustomAttribute) iterator.next();
        em.remove(customAttribute);
        CustomAttributeLanguage customAttributeLanguage = customAttribute.getCustomAttributeLanguage();
        customAttributeLanguage.setCustomAttribute(null);
        em.remove(customAttributeLanguage);
    }

    sql = "from SiteDomain siteDomain where siteDomain.site.siteId = :siteId";
    query = em.createQuery(sql);
    query.setParameter("siteId", site.getSiteId());
    iterator = query.getResultList().iterator();
    while (iterator.hasNext()) {
        SiteDomain siteDomain = (SiteDomain) iterator.next();
        for (SiteDomainLanguage siteDomainLanguage : siteDomain.getSiteDomainLanguages()) {
            em.remove(siteDomainLanguage);
        }
        em.remove(siteDomain);
    }
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

@Override
public void deletePropValue(Object propFieldId, Object propValueId) {
    EntityManager em = this.emf.createEntityManager();
    try {//from   www.  ja  v a  2 s  . c  o  m
        Long longId = LongUserType.massageToLong(propValueId);
        PropValue pv = em.find(PropValue.class, longId);
        if (pv != null) {
            PropField propField = getPropField(pv.getPropField().getId());
            propField.getPropValues().remove(pv);
            em.getTransaction().begin();
            em.remove(pv);
            propField = em.merge(propField);
            em.getTransaction().commit();
        }
    } finally {
        cleanup(em);
    }
}

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

public void deleteService(DeleteService body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {//  ww  w . ja  v a  2  s . c  o m
        tx.begin();

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

        new ValidatePublish(publisher).validateDeleteService(em, body);

        List<String> entityKeyList = body.getServiceKey();
        for (String entityKey : entityKeyList) {
            Object obj = em.find(org.apache.juddi.model.BusinessService.class, entityKey);

            ((org.apache.juddi.model.BusinessService) obj).getBusinessEntity()
                    .setModifiedIncludingChildren(new Date());

            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(PublicationQuery.DELETE_SERVICE, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

public void deleteSubscription(DeleteSubscription body) throws DispositionReportFaultMessage {
    long startTime = System.currentTimeMillis();

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

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

        List<String> subscriptionKeyList = body.getSubscriptionKey();
        for (String subscriptionKey : subscriptionKeyList) {
            Object obj = em.find(org.apache.juddi.model.Subscription.class, subscriptionKey);
            em.remove(obj);
        }

        tx.commit();
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, QueryStatus.SUCCESS, procTime);
    } catch (DispositionReportFaultMessage drfm) {
        long procTime = System.currentTimeMillis() - startTime;
        serviceCounter.update(SubscriptionQuery.DELETE_SUBSCRIPTION, QueryStatus.FAILED, procTime);
        throw drfm;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:com.intuit.tank.dao.ScriptDao.java

/**
 * @{inheritDoc//  w  ww.j a  va  2  s.c o  m
 */
@Override
public void delete(Integer id) throws HibernateException {
    EntityManager em = getEntityManager();
    begin();
    try {
        Script entity = em.find(Script.class, id);
        if (entity != null) {
            // check if it is used in scriptGroups
            List<ScriptGroupStep> scriptGroupsForScript = new ScriptGroupStepDao()
                    .getScriptGroupsForScript(entity);
            if (!scriptGroupsForScript.isEmpty()) {
                StringBuilder sb = new StringBuilder();
                for (ScriptGroupStep step : scriptGroupsForScript) {
                    Project p = extractProject(step);
                    if (sb.length() != 0) {
                        sb.append(", ");
                    }
                    if (p != null) {
                        sb.append(p.getName()).append(" (id=").append(p.getId()).append(")");
                    } else {
                        sb.append("unknown project");
                    }
                }
                if (sb.length() > 0) {
                    // throw exception
                    throw new IllegalArgumentException("Cannot delete script " + entity.getName()
                            + " because it is used in the following projects: " + sb.toString());
                }
            }
            LOG.debug("deleting entity " + entity.toString());
            em.remove(entity);
            commit();
        }
    } finally {
        cleanup();
    }
}