Example usage for javax.persistence Query executeUpdate

List of usage examples for javax.persistence Query executeUpdate

Introduction

In this page you can find the example usage for javax.persistence Query executeUpdate.

Prototype

int executeUpdate();

Source Link

Document

Execute an update or delete statement.

Usage

From source file:io.apiman.manager.api.jpa.JpaStorage.java

private void deleteAllContracts(ClientBean clientBean) throws StorageException {
    Query query;

    if (isMySql()) {
        String sql = "DELETE c " + "    FROM contracts c " + "    JOIN client_versions "
                + "        ON c.clientv_id = client_versions.id " + "    JOIN clients "
                + "        ON client_versions.client_id = clients.id "
                + "        AND client_versions.client_org_id = clients.organization_id "
                + "    JOIN organizations " + "        ON clients.organization_id = organizations.id "
                + "WHERE organizations.id = :orgId " + "AND clients.id = :clientId ;";
        query = getActiveEntityManager().createNativeQuery(sql);
    } else {/*w  ww .  ja  v a  2s  .c om*/
        String jpql = "DELETE ContractBean deleteBean " + "   WHERE deleteBean IN ( " + "       SELECT b "
                + "           FROM ContractBean b " + "           JOIN b.client clientVersion "
                + "           JOIN clientVersion.client client " + "           JOIN client.organization o "
                + "       WHERE o.id = :orgId " + "       AND client.id = :clientId " + "   )";
        query = getActiveEntityManager().createQuery(jpql);
    }

    query.setParameter("orgId", clientBean.getOrganization().getId());
    query.setParameter("clientId", clientBean.getId());
    query.executeUpdate();
}

From source file:org.rhq.enterprise.server.content.ContentSourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public RepoSyncResults _mergePackageSyncReportREMOVE(ContentSource contentSource, Repo repo,
        PackageSyncReport report, Map<ContentProviderPackageDetailsKey, PackageVersionContentSource> previous,
        RepoSyncResults syncResults, StringBuilder progress) {

    progress.append(new Date()).append(": ").append("Removing");
    syncResults.setResults(progress.toString());
    syncResults = repoManager.mergeRepoSyncResults(syncResults);

    Query q;
    int flushCount = 0; // used to know when we should flush the entity manager - for performance purposes
    int removeCount = 0;

    // remove all packages that are no longer available on the remote repository
    // for each removed package, we need to purge the PVCS mapping and the PV itself

    for (ContentProviderPackageDetails doomedDetails : report.getDeletedPackages()) {

        // Delete the mapping between package version and content source
        ContentProviderPackageDetailsKey doomedDetailsKey = doomedDetails.getContentProviderPackageDetailsKey();
        PackageVersionContentSource doomedPvcs = previous.get(doomedDetailsKey);
        doomedPvcs = entityManager.find(PackageVersionContentSource.class,
                doomedPvcs.getPackageVersionContentSourcePK());
        if (doomedPvcs != null) {
            entityManager.remove(doomedPvcs);
        }//from  w  w w  .  j  a v a 2s  .co  m

        // Delete the relationship between package and repo IF no other providers provide the
        // package
        q = entityManager.createNamedQuery(RepoPackageVersion.DELETE_WHEN_NO_PROVIDER);
        q.setParameter("repoId", repo.getId());
        q.executeUpdate();

        // Delete the package version if it is sufficiently orphaned:
        // - No repos
        // - No content sources
        // - No installed packages
        PackageVersion doomedPv = doomedPvcs.getPackageVersionContentSourcePK().getPackageVersion();
        q = entityManager.createNamedQuery(PackageVersion.DELETE_SINGLE_IF_NO_CONTENT_SOURCES_OR_REPOS);
        q.setParameter("packageVersionId", doomedPv.getId());
        q.executeUpdate();

        if ((++flushCount % 200) == 0) {
            entityManager.flush();
            entityManager.clear();
        }

        if ((++removeCount % 200) == 0) {
            progress.append("...").append(removeCount);
            syncResults.setResults(progress.toString());
            syncResults = repoManager.mergeRepoSyncResults(syncResults);
        }
    }

    progress.append("...").append(removeCount).append('\n');
    syncResults.setResults(progress.toString());
    syncResults = repoManager.mergeRepoSyncResults(syncResults);

    return syncResults;
}

From source file:org.opencms.db.jpa.CmsVfsDriver.java

/**
 * @see org.opencms.db.I_CmsVfsDriver#createOnlineContent(org.opencms.db.CmsDbContext, org.opencms.util.CmsUUID, byte[], int, boolean, boolean)
 *///from   ww w.j  a va  2  s.c  om
public void createOnlineContent(CmsDbContext dbc, CmsUUID resourceId, byte[] contents, int publishTag,
        boolean keepOnline, boolean needToUpdateContent) throws CmsDataAccessException {

    try {
        boolean dbcHasProjectId = (dbc.getProjectId() != null) && !dbc.getProjectId().isNullUUID();

        if (needToUpdateContent || dbcHasProjectId) {
            if (dbcHasProjectId || !OpenCms.getSystemInfo().isHistoryEnabled()) {
                // remove the online content for this resource id
                Query q = m_sqlManager.createQuery(dbc, "C_ONLINE_CONTENTS_DELETE");
                q.setParameter(1, resourceId.toString());
                q.executeUpdate();
            } else {
                // put the online content in the history, only if explicit requested
                Query q = m_sqlManager.createQuery(dbc, "C_ONLINE_CONTENTS_HISTORY");
                q.setParameter(1, resourceId.toString());
                @SuppressWarnings("unchecked")
                List<CmsDAOContents> res = q.getResultList();
                for (CmsDAOContents c : res) {
                    c.setOnlineFlag(0);
                }
            }

            // create new online content
            CmsDAOContents c = new CmsDAOContents();

            c.setResourceId(resourceId.toString());
            c.setFileContent(contents);
            c.setPublishTagFrom(publishTag);
            c.setPublishTagTo(publishTag);
            c.setOnlineFlag(keepOnline ? 1 : 0);

            m_sqlManager.persist(dbc, c);
        } else {
            // update old content entry
            Query q = m_sqlManager.createQuery(dbc, C_HISTORY_CONTENTS_UPDATE);
            q.setParameter(1, resourceId.toString());
            @SuppressWarnings("unchecked")
            List<CmsDAOContents> res = q.getResultList();
            for (CmsDAOContents c : res) {
                c.setPublishTagTo(publishTag);
            }

            if (!keepOnline) {
                // put the online content in the history 
                q = m_sqlManager.createQuery(dbc, C_ONLINE_CONTENTS_HISTORY);
                q.setParameter(1, resourceId.toString());
                @SuppressWarnings("unchecked")
                List<CmsDAOContents> res1 = q.getResultList();
                for (CmsDAOContents c : res1) {
                    c.setOnlineFlag(0);
                }
            }
        }
    } catch (PersistenceException e) {
        throw new CmsDataAccessException(Messages.get().container(Messages.ERR_JPA_PERSITENCE, e), e);
    }
}

From source file:org.rhq.enterprise.server.alert.AlertManagerBean.java

@RequiredPermission(Permission.MANAGE_SETTINGS)
public int deleteAlertsByContext(Subject subject, EntityContext context) {
    Query deleteConditionLogsQuery = null;
    Query deleteNotificationLogsQuery = null;
    Query deleteAlertsQuery = null;

    if (context.type == EntityContext.Type.Resource) {
        if (!authorizationManager.hasResourcePermission(subject, Permission.MANAGE_ALERTS,
                context.resourceId)) {//from   www.j a v a  2s .co  m
            throw new PermissionException("Can not delete alerts - " + subject + " lacks "
                    + Permission.MANAGE_ALERTS + " for resource[id=" + context.resourceId + "]");
        }
        deleteConditionLogsQuery = entityManager.createNamedQuery(AlertConditionLog.QUERY_DELETE_BY_RESOURCES);
        deleteConditionLogsQuery.setParameter("resourceIds", Arrays.asList(context.resourceId));

        deleteNotificationLogsQuery = entityManager
                .createNamedQuery(AlertNotificationLog.QUERY_DELETE_BY_RESOURCES);
        deleteNotificationLogsQuery.setParameter("resourceIds", Arrays.asList(context.resourceId));

        deleteAlertsQuery = entityManager.createNamedQuery(Alert.QUERY_DELETE_BY_RESOURCES);
        deleteAlertsQuery.setParameter("resourceIds", Arrays.asList(context.resourceId));

    } else if (context.type == EntityContext.Type.ResourceGroup) {
        if (!authorizationManager.hasGroupPermission(subject, Permission.MANAGE_ALERTS, context.groupId)) {
            throw new PermissionException("Can not delete alerts - " + subject + " lacks "
                    + Permission.MANAGE_ALERTS + " for group[id=" + context.groupId + "]");
        }
        deleteConditionLogsQuery = entityManager
                .createNamedQuery(AlertConditionLog.QUERY_DELETE_BY_RESOURCE_GROUPS);
        deleteConditionLogsQuery.setParameter("groupIds", Arrays.asList(context.groupId));

        deleteNotificationLogsQuery = entityManager
                .createNamedQuery(AlertNotificationLog.QUERY_DELETE_BY_RESOURCE_GROUPS);
        deleteNotificationLogsQuery.setParameter("groupIds", Arrays.asList(context.groupId));

        deleteAlertsQuery = entityManager.createNamedQuery(Alert.QUERY_DELETE_BY_RESOURCE_GROUPS);
        deleteAlertsQuery.setParameter("groupIds", Arrays.asList(context.groupId));

    } else if (context.type == EntityContext.Type.SubsystemView) {
        if (!authorizationManager.isInventoryManager(subject)) {
            throw new PermissionException("Can not delete alerts - " + subject + " lacks "
                    + Permission.MANAGE_INVENTORY + " for global alerts history");
        }
        deleteConditionLogsQuery = entityManager.createNamedQuery(AlertConditionLog.QUERY_DELETE_ALL);
        deleteNotificationLogsQuery = entityManager.createNamedQuery(AlertNotificationLog.QUERY_DELETE_ALL);
        deleteAlertsQuery = entityManager.createNamedQuery(Alert.QUERY_DELETE_ALL);
    } else if (context.type == EntityContext.Type.ResourceTemplate) {
        // TODO Need to determine what security check(s) need to be performed here
        deleteAlertsQuery = entityManager.createNamedQuery(Alert.QUERY_DELETE_BY_RESOURCE_TEMPLATE);
        deleteAlertsQuery.setParameter("resourceTypeId", context.resourceTypeId);

        deleteConditionLogsQuery = entityManager
                .createNamedQuery(AlertConditionLog.QUERY_DELETE_BY_RESOURCE_TEMPLATE);
        deleteConditionLogsQuery.setParameter("resourceTypeId", context.resourceTypeId);

        deleteNotificationLogsQuery = entityManager
                .createNamedQuery(AlertNotificationLog.QUERY_DELETE_BY_RESOURCE_TEMPLATE);
        deleteNotificationLogsQuery.setParameter("resourceTypeId", context.resourceTypeId);

    } else {
        throw new IllegalArgumentException("No support for deleting alerts for " + context);
    }

    deleteConditionLogsQuery.executeUpdate();
    deleteNotificationLogsQuery.executeUpdate();
    int affectedRows = deleteAlertsQuery.executeUpdate();
    return affectedRows;
}

From source file:org.opencms.db.jpa.CmsVfsDriver.java

/**
 * @see org.opencms.db.I_CmsVfsDriver#removeFile(org.opencms.db.CmsDbContext, CmsUUID, org.opencms.file.CmsResource)
 *///ww w.  ja  va 2s. co m
public void removeFile(CmsDbContext dbc, CmsUUID projectId, CmsResource resource)
        throws CmsDataAccessException {

    int siblingCount = 0;

    try {
        // delete the structure record
        Query q = m_sqlManager.createQuery(dbc, projectId, C_STRUCTURE_DELETE_BY_STRUCTUREID);
        q.setParameter(1, resource.getStructureId().toString());
        @SuppressWarnings("unchecked")
        List<I_CmsDAOStructure> res = q.getResultList();
        for (I_CmsDAOStructure ps : res) {
            m_sqlManager.remove(dbc, ps);
        }

        // count the references to the resource
        siblingCount = countSiblings(dbc, projectId, resource.getResourceId());

        if (siblingCount > 0) {
            // update the link Count
            q = m_sqlManager.createQuery(dbc, projectId, C_RESOURCES_UPDATE_SIBLING_COUNT);
            q.setParameter(1, resource.getResourceId().toString());
            @SuppressWarnings("unchecked")
            List<I_CmsDAOResources> ress = q.getResultList();

            for (I_CmsDAOResources r : ress) {
                r.setSiblingCount(siblingCount);
            }

            // update the resource flags
            q = m_sqlManager.createQuery(dbc, projectId, C_RESOURCES_UPDATE_FLAGS);
            q.setParameter(1, resource.getResourceId().toString());
            @SuppressWarnings("unchecked")
            List<I_CmsDAOResources> resf = q.getResultList();

            for (I_CmsDAOResources r : resf) {
                r.setResourceFlags(resource.getFlags());
            }

        } else {
            // if not referenced any longer, also delete the resource and the content record
            q = m_sqlManager.createQuery(dbc, projectId, C_RESOURCES_DELETE_BY_RESOURCEID);
            q.setParameter(1, resource.getResourceId().toString());
            @SuppressWarnings("unchecked")
            List<I_CmsDAOResources> res1 = q.getResultList();
            for (I_CmsDAOResources pr : res1) {
                m_sqlManager.remove(dbc, pr);
            }

            boolean dbcHasProjectId = (dbc.getProjectId() != null) && !dbc.getProjectId().isNullUUID();

            // if online we have to keep historical content
            if (projectId.equals(CmsProject.ONLINE_PROJECT_ID)) {
                // put the online content in the history 
                q = m_sqlManager.createQuery(dbc, C_ONLINE_CONTENTS_HISTORY);
                q.setParameter(1, resource.getResourceId().toString());
                @SuppressWarnings("unchecked")
                List<CmsDAOContents> res2 = q.getResultList();
                for (CmsDAOContents c : res2) {
                    c.setOnlineFlag(0);
                }
            } else if (dbcHasProjectId) {
                // remove current online version
                q = m_sqlManager.createQuery(dbc, C_ONLINE_CONTENTS_DELETE);
                q.setParameter(1, resource.getResourceId().toString());
                q.executeUpdate();
            } else {
                // delete content records with this resource id
                q = m_sqlManager.createQuery(dbc, C_OFFLINE_FILE_CONTENT_DELETE);
                q.setParameter(1, resource.getResourceId().toString());
                q.executeUpdate();
            }
        }
    } catch (PersistenceException e) {
        throw new CmsDataAccessException(Messages.get().container(Messages.ERR_JPA_PERSITENCE, e), e);
    }
}