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:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java

/**
 * @inheritDoc//  ww w .  j  a va  2 s.c  om
 */
public void updateTagCount(String name, Weblog website, int amount) throws WebloggerException {
    if (amount == 0) {
        throw new WebloggerException("Tag increment amount cannot be zero.");
    }

    if (website == null) {
        throw new WebloggerException("Website cannot be NULL.");
    }

    // The reason why add order lastUsed desc is to make sure we keep picking the most recent
    // one in the case where we have multiple rows (clustered environment)
    // eventually that second entry will have a very low total (most likely 1) and
    // won't matter
    Query weblogQuery = strategy.getNamedQuery("WeblogEntryTagAggregate.getByName&WebsiteOrderByLastUsedDesc");
    weblogQuery.setParameter(1, name);
    weblogQuery.setParameter(2, website);
    WeblogEntryTagAggregate weblogTagData;
    try {
        weblogTagData = (WeblogEntryTagAggregate) weblogQuery.getSingleResult();
    } catch (NoResultException e) {
        weblogTagData = null;
    }

    Query siteQuery = strategy
            .getNamedQuery("WeblogEntryTagAggregate.getByName&WebsiteNullOrderByLastUsedDesc");
    siteQuery.setParameter(1, name);
    WeblogEntryTagAggregate siteTagData;
    try {
        siteTagData = (WeblogEntryTagAggregate) siteQuery.getSingleResult();
    } catch (NoResultException e) {
        siteTagData = null;
    }
    Timestamp lastUsed = new Timestamp((new Date()).getTime());

    // create it only if we are going to need it.
    if (weblogTagData == null && amount > 0) {
        weblogTagData = new WeblogEntryTagAggregate(null, website, name, amount);
        weblogTagData.setLastUsed(lastUsed);
        strategy.store(weblogTagData);

    } else if (weblogTagData != null) {
        weblogTagData.setTotal(weblogTagData.getTotal() + amount);
        weblogTagData.setLastUsed(lastUsed);
        strategy.store(weblogTagData);
        // Why use update query when only one object needs update?
        //            Query update = strategy.getNamedUpdate(
        //                    "WeblogEntryTagAggregate.updateAddToTotalByName&Weblog");
        //            update.setParameter(1, new Long(amount));
        //            update.setParameter(2, lastUsed);
        //            update.setParameter(3, weblogTagData.getName());
        //            update.setParameter(4, website);
        //            update.executeUpdate();
    }

    // create it only if we are going to need it.
    if (siteTagData == null && amount > 0) {
        siteTagData = new WeblogEntryTagAggregate(null, null, name, amount);
        siteTagData.setLastUsed(lastUsed);
        strategy.store(siteTagData);

    } else if (siteTagData != null) {
        siteTagData.setTotal(siteTagData.getTotal() + amount);
        siteTagData.setLastUsed(lastUsed);
        strategy.store(siteTagData);
        // Why use update query when only one object needs update?
        //            Query update = strategy.getNamedUpdate(
        //                    "WeblogEntryTagAggregate.updateAddToTotalByName&WeblogNull");
        //            update.setParameter(1, new Long(amount));
        //            update.setParameter(2, siteTagData.getName());
        //            update.executeUpdate();
    }

    // delete all bad counts
    Query removeq = strategy.getNamedUpdate("WeblogEntryTagAggregate.removeByTotalLessEqual");
    removeq.setParameter(1, new Integer(0));
    removeq.executeUpdate();
}

From source file:com.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

public int updateProductCertByBarcode(String barcode, int cert) {
    String sql = "update product set product_certification=" + cert + " where barcode='" + barcode + "'";
    Query query = entityManager.createNativeQuery(sql);
    return query.executeUpdate();
}

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

/**
 * Acknowledge alert(s) so that administrators know who is working on remedying the underlying
 * condition(s) that caused the alert(s) in the first place.
 *
 * @param subject calling user//www .ja  v a 2s . co  m
 * @param alertIds PKs of the alerts to acknowledge
 * @return number of alerts acknowledged
 */
public int acknowledgeAlerts(Subject subject, int[] alertIds) {
    if (alertIds == null || alertIds.length == 0) {
        return 0;
    }

    List<Integer> alertIdList = ArrayUtils.wrapInList(alertIds);

    checkAlertsPermission(subject, alertIdList);

    Query ackAlertsQuery = entityManager.createNamedQuery(Alert.QUERY_ACKNOWLEDGE_BY_IDS);
    ackAlertsQuery.setParameter("subjectName", subject.getName());
    ackAlertsQuery.setParameter("ackTime", System.currentTimeMillis());

    int modified = 0;
    BatchIterator<Integer> batchIter = new BatchIterator<Integer>(alertIdList);
    for (List<Integer> nextBatch : batchIter) {
        ackAlertsQuery.setParameter("alertIds", nextBatch);
        modified += ackAlertsQuery.executeUpdate();
    }
    return modified;
}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

private void setAgentSynchronizationNeededByDefinitionsForAgent(int agentId,
        List<Integer> measurementDefinitionIds) {
    String updateSQL = "" //
            + "UPDATE Resource res " //
            + "   SET res.mtime = :now " //
            + " WHERE res.agent.id = :agentId AND " //
            + "       res.resourceType.id IN ( SELECT md.resourceType.id " //
            + "                                  FROM MeasurementDefinition md " //
            + "                                 WHERE md.id IN ( :definitionIds ) )";
    Query updateQuery = entityManager.createQuery(updateSQL);
    updateQuery.setParameter("now", System.currentTimeMillis());
    updateQuery.setParameter("agentId", agentId);
    updateQuery.setParameter("definitionIds", measurementDefinitionIds);
    int updateCount = updateQuery.executeUpdate();

    if (log.isDebugEnabled()) {
        log.debug("" + updateCount
                + " resources mtime fields were updated as a result of this metric template update");
    }//from  www. ja  v  a2s  .  com
}

From source file:org.cesecore.certificates.certificate.CertificateStoreSessionBean.java

License:asdf

/** Remove limited CertificateData by fingerprint (and ensures that this is not a full entry by making sure that subjectKeyId is NULL */
private boolean deleteLimitedCertificateData(final String fingerprint) {
    log.info("Removing CertificateData entry with fingerprint=" + fingerprint
            + " and no subjectKeyId is defined.");
    final Query query = entityManager.createQuery(
            "DELETE FROM CertificateData a WHERE a.fingerprint=:fingerprint AND subjectKeyId IS NULL");
    query.setParameter("fingerprint", fingerprint);
    final int deletedRows = query.executeUpdate();
    if (log.isDebugEnabled()) {
        log.debug("Deleted " + deletedRows + " rows with fingerprint " + fingerprint);
    }/*  w  w  w . ja va 2s  . co  m*/
    return deletedRows == 1;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogEntryManagerImpl.java

/**
 * @inheritDoc/*from  w  w w  . ja  v a  2  s  . c o m*/
 */
public void applyCommentDefaultsToEntries(Weblog website) throws WebloggerException {
    if (log.isDebugEnabled()) {
        log.debug("applyCommentDefaults");
    }

    // TODO: Non-standard JPA bulk update, using parameter values in set clause
    Query q = strategy.getNamedUpdate("WeblogEntry.updateAllowComments&CommentDaysByWebsite");
    q.setParameter(1, website.getDefaultAllowComments());
    q.setParameter(2, new Integer(website.getDefaultCommentDays()));
    q.setParameter(3, website);
    q.executeUpdate();
}

From source file:com.gettec.fsnip.fsn.dao.product.impl.ProductDAOImpl.java

@Override
public boolean deleteBarcodeToQRcode(Long id) throws DaoException {
    try {/*  w w  w.  jav a 2s  .  c  o  m*/

        String sql = " DELETE  FROM product_barcode_to_qrcode WHERE id=?1 ";
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter(1, id);
        int success = query.executeUpdate();
        if (success > 0) {
            return true;
        }

        else {
            return false;
        }

    } catch (Exception e) {
        throw new DaoException("ProductDAOImpl.getBarcodeToQRcode() ?", e);
    }
}

From source file:org.rhq.enterprise.server.bundle.BundleManagerBean.java

@Override
@RequiredPermission(Permission.MANAGE_BUNDLE)
public void deleteBundleDestination(Subject subject, int destinationId) throws Exception {
    BundleDestination doomed = this.entityManager.find(BundleDestination.class, destinationId);
    if (null == doomed) {
        return;/*from  ww w  .  j a  va 2s  .  com*/
    }

    // deployments replace other deployments and have a self-referring FK.  The deployments
    // need to be removed in a way that will ensure that a replaced deployment is not removed
    // prior to the replacer.  To do this we'll just blanket update all the doomed deployments
    // to break the FK dependency with nulls.
    Query q = entityManager.createNamedQuery(BundleDeployment.QUERY_UPDATE_FOR_DESTINATION_REMOVE);
    q.setParameter("destinationId", destinationId);
    q.executeUpdate();
    entityManager.flush();

    entityManager.remove(doomed);
}

From source file:org.rhq.enterprise.server.resource.group.ResourceGroupManagerBean.java

@RequiredPermission(Permission.MANAGE_INVENTORY)
public void deleteResourceGroup(Subject subject, int groupId)
        throws ResourceGroupNotFoundException, ResourceGroupDeleteException {
    ResourceGroup group = getResourceGroupById(subject, groupId, null);

    for (Role doomedRoleRelationship : group.getRoles()) {
        group.removeRole(doomedRoleRelationship);
        entityManager.merge(doomedRoleRelationship);
    }//  ww  w  . j  a v  a 2s .  co m

    // remove all resources in the group
    resourceGroupManager.removeAllResourcesFromGroup(subject, groupId);

    if (group.getGroupCategory() == GroupCategory.COMPATIBLE) {
        removeCompatibleGroupConstructs(subject, group);
    }

    // break resource and plugin configuration update links in order to preserve individual change history
    Query q = null;

    q = entityManager.createNamedQuery(ResourceConfigurationUpdate.QUERY_DELETE_GROUP_UPDATES_FOR_GROUP);
    q.setParameter("groupId", group.getId());
    q.executeUpdate();

    q = entityManager.createNamedQuery(PluginConfigurationUpdate.QUERY_DELETE_GROUP_UPDATES_FOR_GROUP);
    q.setParameter("groupId", group.getId());
    q.executeUpdate();

    entityManager.remove(group);
}

From source file:org.rhq.enterprise.server.bundle.BundleManagerBean.java

@Override
@RequiredPermission(Permission.MANAGE_BUNDLE)
public void deleteBundleVersion(Subject subject, int bundleVersionId, boolean deleteBundleIfEmpty)
        throws Exception {
    BundleVersion bundleVersion = this.entityManager.find(BundleVersion.class, bundleVersionId);
    if (null == bundleVersion) {
        return;//from ww w  .j  ava 2  s . c o  m
    }

    int bundleId = 0;
    if (deleteBundleIfEmpty) {
        bundleId = bundleVersion.getBundle().getId(); // note that we lazy load this if we never plan to delete the bundle
    }

    // deployments replace other deployments and have a self-referring FK.  The deployments
    // need to be removed in a way that will ensure that a replaced deployment is not removed
    // prior to the replacer.  To do this we'll just blanket update all the doomed deployments
    // to break the FK dependency with nulls.
    Query q = entityManager.createNamedQuery(BundleDeployment.QUERY_UPDATE_FOR_VERSION_REMOVE);
    q.setParameter("bundleVersionId", bundleVersionId);
    @SuppressWarnings("unused")
    int rowsUpdated = q.executeUpdate();
    entityManager.flush();

    // remove the bundle version - cascade remove the deployments which will cascade remove the resource deployments.
    this.entityManager.remove(bundleVersion);

    if (deleteBundleIfEmpty) {
        this.entityManager.flush();
        q = entityManager.createNamedQuery(BundleVersion.QUERY_FIND_VERSION_INFO_BY_BUNDLE_ID);
        q.setParameter("bundleId", bundleId);
        if (q.getResultList().size() == 0) {
            // there are no more bundle versions left, blow away the bundle and all repo/bundle files associated with it
            deleteBundle(subject, bundleId);
        }
    }

    return;
}