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.rhq.enterprise.server.resource.group.LdapGroupManagerBean.java

@RequiredPermission(Permission.MANAGE_SECURITY)
public void removeLdapGroupsFromRole(Subject subject, int roleId, int[] groupIds) {
    if ((groupIds != null) && (groupIds.length > 0)) {
        Role role = entityManager.find(Role.class, roleId);
        if (role == null) {
            throw new IllegalArgumentException(
                    "Could not find role[" + roleId + "] to remove LDAP groups from.");
        }/*from  w  w w.  j a  v  a  2 s  .c o  m*/
        role.getLdapGroups().size(); // load them in

        for (Integer groupId : groupIds) {
            LdapGroup doomedGroup = entityManager.find(LdapGroup.class, groupId);
            if (doomedGroup == null) {
                throw new IllegalArgumentException("Tried to remove doomedGroup[" + groupId + "] from role["
                        + roleId + "], but doomedGroup was not found.");
            }
            role.removeLdapGroup(doomedGroup);
        }

        Query purgeQuery = entityManager.createNamedQuery(LdapGroup.DELETE_BY_ID);

        List<Integer> ids = new LinkedList<Integer>();
        for (int i : groupIds) {
            ids.add(i);
        }
        purgeQuery.setParameter("ids", ids);
        purgeQuery.executeUpdate();
    }
}

From source file:org.apache.openmeetings.data.user.dao.PrivateMessagesDao.java

public int updatePrivateMessagesReadStatus(List<Long> privateMessageIds, Boolean isRead) {
    try {//from  w  w w . j a  v  a  2s .  c  o m
        Query query = em.createNamedQuery("updatePrivateMessagesReadStatus");
        query.setParameter("isRead", isRead);
        query.setParameter("privateMessageIds", privateMessageIds);
        int updatedEntities = query.executeUpdate();

        //Refresh the Entities in the Cache as Hibernate will not do it!
        //FIXME weird code
        for (Long privateMessageId : privateMessageIds) {
            TypedQuery<PrivateMessage> querySel = em.createNamedQuery("getPrivateMessagesById",
                    PrivateMessage.class);
            querySel.setParameter("privateMessageId", privateMessageId);
            try {
                querySel.getSingleResult();
            } catch (NoResultException ex) {
            }
        }
        return updatedEntities;
    } catch (Exception e) {
        log.error("[updatePrivateMessagesReadStatus]", e);
    }
    return -1;
}

From source file:org.rhq.enterprise.server.core.AgentManagerBean.java

private void updateLastAvailabilityPing(String agentName, long now) {
    /*/*w ww. j  ava  2s .  c o  m*/
     * since we already know we have to update the agent row with the last avail ping time, might as well 
     * set the backfilled to false here (as opposed to called agentManager.setBackfilled(agentId, false)
     */
    String updateStatement = "" //
            + "UPDATE Agent " //
            + "   SET lastAvailabilityPing = :now, backFilled = FALSE " //
            + " WHERE name = :agentName ";

    Query query = entityManager.createQuery(updateStatement);
    query.setParameter("now", now);
    query.setParameter("agentName", agentName);

    query.executeUpdate();
}

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

public void massReconfigure(List<Integer> alertNotificationIds, Map<String, String> newConfigurationValues) {
    Query query = entityManager.createNamedQuery(AlertNotification.QUERY_UPDATE_PARAMETER_FOR_NOTIFICATIONS);

    query.setParameter("alertNotificationIds", alertNotificationIds);

    for (Map.Entry<String, String> entry : newConfigurationValues.entrySet()) {
        query.setParameter("propertyName", entry.getKey());
        query.setParameter("propertyValue", entry.getValue());

        query.executeUpdate();
    }/* w ww . jav  a  2 s  .c  om*/
}

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

/**
 * Try to aquire a lock for a given RollerTask.
 *//*from  w  w  w .ja v  a2 s . c o m*/
@Override
public boolean registerLease(RollerTask task) {

    log.debug("Attempting to register lease for task - " + task.getName());

    // keep a copy of the current time
    Date currentTime = new Date();

    // query for existing lease record first
    TaskLock taskLock = null;
    try {
        taskLock = getTaskLockByName(task.getName());
        if (taskLock == null) {
            log.warn("Cannot acquire lease when no tasklock record exists for task - " + task.getName());
        }
    } catch (WebloggerException ex) {
        log.warn("Error getting TaskLock", ex);
        return false;
    }

    // try to acquire lease
    if (taskLock != null)
        try {
            // calculate lease expiration time
            Date leaseExpiration = taskLock.getLeaseExpiration();

            // calculate run time for task, this is expected time, not actual time
            // i.e. if a task is meant to run daily at midnight this should
            // reflect 00:00:00 on the current day
            Date runTime = currentTime;
            if ("startOfDay".equals(task.getStartTimeDesc())) {
                // start of today
                runTime = DateUtil.getStartOfDay(currentTime);
            } else if ("startOfHour".equals(task.getStartTimeDesc())) {
                // start of this hour
                runTime = DateUtil.getStartOfHour(currentTime);
            } else {
                // start of this minute
                runTime = DateUtil.getStartOfMinute(currentTime);
            }

            if (log.isDebugEnabled()) {
                log.debug("last run = " + taskLock.getLastRun());
                log.debug("new run time = " + runTime);
                log.debug("last acquired = " + taskLock.getTimeAquired());
                log.debug("time leased = " + taskLock.getTimeLeased());
                log.debug("lease expiration = " + leaseExpiration);
            }

            Query q = strategy
                    .getNamedUpdate("TaskLock.updateClient&Timeacquired&Timeleased&LastRunByName&Timeacquired");
            q.setParameter(1, task.getClientId());
            q.setParameter(2, Integer.valueOf(task.getLeaseTime()));
            q.setParameter(3, new Timestamp(runTime.getTime()));
            q.setParameter(4, task.getName());
            q.setParameter(5, taskLock.getTimeAquired());
            q.setParameter(6, new Timestamp(leaseExpiration.getTime()));
            int result = q.executeUpdate();

            if (result == 1) {
                strategy.flush();
                return true;
            }

        } catch (Exception e) {
            log.warn("Error obtaining lease, assuming race condition.", e);
            return false;
        }

    return false;
}

From source file:org.rhq.enterprise.server.drift.JPADriftServerBean.java

@Override
@TransactionAttribute(REQUIRES_NEW)//from   w  w  w .  j a va  2  s  .  c o m
public void purgeByDriftDefinitionName(Subject subject, int resourceId, String driftDefName) throws Exception {

    int driftsDeleted;
    int changeSetsDeleted;
    StopWatch timer = new StopWatch();

    // purge all drift entities first
    Query q = entityManager.createNamedQuery(JPADrift.QUERY_DELETE_BY_DRIFTDEF_RESOURCE);
    q.setParameter("resourceId", resourceId);
    q.setParameter("driftDefinitionName", driftDefName);
    driftsDeleted = q.executeUpdate();

    // delete the drift set
    //        JPADriftChangeSet changeSet = entityManager.createQuery(
    //            "select c from JPADriftChangeSet c where c.version = 0 and c.driftDefinition")

    // now purge all changesets
    q = entityManager.createNamedQuery(JPADriftChangeSet.QUERY_DELETE_BY_DRIFTDEF_RESOURCE);
    q.setParameter("resourceId", resourceId);
    q.setParameter("driftDefinitionName", driftDefName);
    changeSetsDeleted = q.executeUpdate();

    log.info("Purged [" + driftsDeleted + "] drift items and [" + changeSetsDeleted
            + "] changesets associated with drift def [" + driftDefName + "] from resource [" + resourceId
            + "]. Elapsed time=[" + timer.getElapsed() + "]ms");
    return;
}

From source file:org.apache.openmeetings.data.user.dao.PrivateMessagesDao.java

public Integer moveMailsToFolder(List<Long> privateMessageIds, Long privateMessageFolderId) {
    try {//from  www . j av  a 2s .  co m
        Query query = em.createNamedQuery("moveMailsToFolder");
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        query.setParameter("privateMessageIds", privateMessageIds);
        int updatedEntities = query.executeUpdate();

        //Refresh the Entities in the Cache as Hibernate will not do it!
        //FIXME weird code
        for (Long privateMessageId : privateMessageIds) {
            TypedQuery<PrivateMessage> querySel = em.createNamedQuery("getPrivateMessagesById",
                    PrivateMessage.class);
            querySel.setParameter("privateMessageId", privateMessageId);
            try {
                querySel.getSingleResult();
            } catch (NoResultException ex) {
            }
        }
        return updatedEntities;
    } catch (Exception e) {
        log.error("[updatePrivateMessagesReadStatus]", e);
    }
    return -1;
}

From source file:org.rhq.enterprise.server.core.AgentManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setAgentBackfilled(int agentId, boolean backfilled) {
    Query query = entityManager.createNamedQuery(Agent.QUERY_SET_AGENT_BACKFILLED);
    query.setParameter("agentId", agentId);
    query.setParameter("backfilled", backfilled);
    query.executeUpdate();
}

From source file:org.openmeetings.app.data.user.dao.PrivateMessagesDaoImpl.java

public int updatePrivateMessagesReadStatus(List<Long> privateMessageIds, Boolean isRead) {
    try {/*from  w w w  . j a  v a 2  s  .c om*/

        String hql = "UPDATE PrivateMessages c " + "SET c.isRead = :isRead "
                + "where c.privateMessageId IN (:privateMessageIds) ";

        Query query = em.createQuery(hql);
        query.setParameter("isRead", isRead);
        query.setParameter("privateMessageIds", privateMessageIds);
        int updatedEntities = query.executeUpdate();

        //Refresh the Entities in the Cache as Hibernate will not do it!
        //FIXME weird code
        for (Long privateMessageId : privateMessageIds) {
            String hqlSel = "select c from PrivateMessages c "
                    + "where c.privateMessageId = :privateMessageId ";

            TypedQuery<PrivateMessages> querySel = em.createQuery(hqlSel, PrivateMessages.class);
            querySel.setParameter("privateMessageId", privateMessageId);

            try {
                querySel.getSingleResult();
            } catch (NoResultException ex) {
            }
        }
        return updatedEntities;
    } catch (Exception e) {
        log.error("[updatePrivateMessagesReadStatus]", e);
    }
    return -1;
}

From source file:org.apache.ode.dao.jpa.OpenJPADAO.java

protected <T> void batchUpdateByIds(Iterator<T> ids, Query query, String parameterName) {
    if (query instanceof OpenJPAQuery) {
        OpenJPAQuery openJpaQuery = (OpenJPAQuery) query;
        int batchSize = openJpaQuery.getFetchPlan().getFetchBatchSize();
        if (__log.isTraceEnabled())
            __log.trace("BATCH fetchBatchSize = " + batchSize);
        List<T> batch = new ArrayList<T>();
        while (ids.hasNext()) {
            for (int i = 0; i < batchSize && ids.hasNext(); i++) {
                batch.add(ids.next());//from w w  w  . j  av  a2s  . c o m
            }
            if (__log.isTraceEnabled())
                __log.trace("BATCH updating " + batch.size() + " objects.");
            query.setParameter(parameterName, batch);
            query.executeUpdate();
            batch.clear();
        }
    }
}