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.cloud.StatusManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void updateByAlertDefinition(Subject subject, int alertDefinitionId) {
    log.debug("About to mark status by alert definition");

    // alert templates and group alert definitions do not represent cache-ready entries
    if (alertDefinitionManager.isResourceAlertDefinition(alertDefinitionId) == false) {
        return;//from   ww  w.  j a  v a 2s  .  c  om
    }

    /* 
     * the old alert definition is needed to know which caches to remove stale entries from; the updated / new
     * alert definition is needed to know which caches need to be reloaded to get the new conditions; by the time
     * this method is called, we only have the updated alert definition, thus it's not possible to intelligently
     * know which of the two caches to reload; so, we need to reload them both to be sure the system is consistent
     */
    markGlobalCache(); // use local references to execute in the same transaction

    Query updateAgentQuery = entityManager.createNamedQuery(Agent.QUERY_UPDATE_STATUS_BY_ALERT_DEFINITION);
    updateAgentQuery.setParameter("alertDefinitionId", alertDefinitionId);
    int agentsUpdated = updateAgentQuery.executeUpdate();

    /*
     * this is informational debugging only - do NOT change the status bits here
     */
    if (log.isDebugEnabled()) {
        AlertDefinition definition = entityManager.find(AlertDefinition.class, alertDefinitionId);
        Agent agent = agentManager.getAgentByResourceId(LookupUtil.getSubjectManager().getOverlord(),
                definition.getResource().getId());
        log.debug("Marking status, agent[id=" + agent.getId() + ", status=" + agent.getStatus()
                + "] for alertDefinition[id=" + alertDefinitionId + "]");

        log.debug("Agents updated: " + agentsUpdated);
    }
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketFilterDAOJpa.java

@Transactional(readOnly = false)
public void saveOrUpdate(final TicketFilter filter) {
    if (filter.getId() == null) {
        this.jpaTemplate.persist(filter);
    } else {/*from w  ww .  j  av  a  2s.c om*/
        this.jpaTemplate.execute(new JpaCallback<TicketFilter>() {
            public TicketFilter doInJpa(EntityManager em) throws PersistenceException {
                TicketFilterDAOJpa.this.deleteFilterItems(em, filter.getId());
                em.merge(filter);
                // WORKAROUND: Jest jaki problem z zapisaniem do bazy pl z dat
                // ustawionych na null, jeli wczeniej miay jak warto... (OpenJPA 1.2.2)
                Query updateQuery = em
                        .createNativeQuery("UPDATE ticket_filters SET begin_date=?1, end_date=?2 WHERE id=?3");
                updateQuery.setParameter(1, filter.getBeginDate());
                updateQuery.setParameter(2, filter.getEndDate());
                updateQuery.setParameter(3, filter.getId());
                updateQuery.executeUpdate();
                return null;
            }
        });
    }
}

From source file:io.github.davejoyce.dao.composite.social.connect.jpa.JpaConnectionRepository.java

/**
 * {@inheritDoc}/*from   w  ww .j av a 2s . co m*/
 */
public void removeConnections(String providerId) {
    Query deleteQuery = entityManager.createQuery(DELETE_CONNECTIONS).setParameter("userId", userId)
            .setParameter("providerId", providerId);
    deleteQuery.executeUpdate();
}

From source file:com.softwarecorporativo.monitoriaifpe.funcionais.atividade.TesteAtividade.java

@Test
public void testeRemoverAtividadesDeMonitoria() {
    Monitoria monitoria = super.entityManager.find(Monitoria.class, 2L);
    Query query = super.entityManager.createQuery("DELETE Atividade AS a WHERE a.monitoria = ?1");
    query.setParameter(1, monitoria);/*  w  ww . j a va 2s.c om*/
    query.executeUpdate();
    TypedQuery<Long> typedQuery = super.entityManager
            .createQuery("SELECT COUNT(a) FROM Atividade a where a.monitoria = :monitoria", Long.class);
    typedQuery.setParameter("monitoria", monitoria);
    Long quantidadeEsperada = 0L;
    Long quantidade = typedQuery.getSingleResult();
    assertEquals(quantidadeEsperada, quantidade);
}

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

/**
 * Try to release the lock for a given RollerTask.
 *///from  ww w. ja  v a  2s .  c o m
@Override
public boolean unregisterLease(RollerTask task) {

    // query for existing lease record first
    TaskLock taskLock = null;
    try {
        taskLock = this.getTaskLockByName(task.getName());

        if (taskLock == null) {
            return false;
        }

    } catch (WebloggerException ex) {
        if (log.isDebugEnabled()) {
            log.debug("Error getting TaskLock", ex);
        } else {
            log.warn("Error getting TaskLock, enable debug for more info");
        }
        return false;
    }

    // try to release lease, just set lease time to 0
    try {
        Query q = strategy.getNamedUpdate("TaskLock.updateTimeLeasedByName&Client");
        q.setParameter(1, Integer.valueOf(0));
        q.setParameter(2, task.getName());
        q.setParameter(3, task.getClientId());
        int result = q.executeUpdate();

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

    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Error releasing lease", e);
        } else {
            log.warn("Error releasing lease, enable debug for more info");
        }
        return false;
    }

    return false;

}

From source file:org.rhq.enterprise.server.cloud.AffinityGroupManagerBean.java

@RequiredPermission(Permission.MANAGE_INVENTORY)
public void removeAgentsFromGroup(Subject subject, Integer[] agentIds) {
    List<Integer> agentIdsList = Arrays.asList(agentIds);

    Query query = entityManager.createNamedQuery(AffinityGroup.QUERY_UPDATE_REMOVE_SPECIFIC_AGENTS);
    query.setParameter("agentIds", agentIdsList);

    query.executeUpdate();

    // Audit each changed affinity group assignment (is this too verbose?)
    for (Integer agentId : agentIdsList) {
        Agent agent = entityManager.find(Agent.class, agentId);
        partitionEventManager.auditPartitionEvent(subject, PartitionEventType.AGENT_AFFINITY_GROUP_REMOVE,
                agent.getName());/*from   w  w  w .  j a  va  2s. c o m*/

    }
    // Now, request a cloud repartitioning due to the affinity group changes
    partitionEventManager.cloudPartitionEventRequest(subject, PartitionEventType.AFFINITY_GROUP_CHANGE,
            PartitionEventType.AGENT_AFFINITY_GROUP_REMOVE.name());
}

From source file:org.medici.bia.dao.usermessage.UserMessageDAOJpaImpl.java

/**
 * {@inheritDoc}// w w w .  j  a  v  a 2s  .c  o m
 */
@Override
public Integer renameAccount(String originalAccount, String newAccount) throws PersistenceException {
    String jpql = "UPDATE UserMessage SET user.account=:newAccount WHERE user.account=:originalAccount";
    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("newAccount", newAccount);
    query.setParameter("originalAccount", originalAccount);

    return query.executeUpdate();
}

From source file:org.medici.bia.dao.usermessage.UserMessageDAOJpaImpl.java

/**
 * {@inheritDoc}//from  w  w w.j a v  a  2s .com
 */
@Override
public Integer renameRecipient(String originalAccount, String newAccount) {
    String jpql = "UPDATE UserMessage SET recipient=:newAccount WHERE recipient=:originalAccount";
    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("newAccount", newAccount);
    query.setParameter("originalAccount", originalAccount);

    return query.executeUpdate();
}

From source file:org.medici.bia.dao.usermessage.UserMessageDAOJpaImpl.java

/**
 * {@inheritDoc}// w w w . ja  v  a  2  s  .  c o m
 */
@Override
public Integer renameSender(String originalAccount, String newAccount) {
    String jpql = "UPDATE UserMessage SET sender=:newAccount WHERE sender=:originalAccount";
    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("newAccount", newAccount);
    query.setParameter("originalAccount", originalAccount);

    return query.executeUpdate();
}

From source file:org.rhq.enterprise.server.cloud.AffinityGroupManagerBean.java

@RequiredPermission(Permission.MANAGE_INVENTORY)
public void removeServersFromGroup(Subject subject, Integer[] serverIds) {
    List<Integer> serverIdsList = Arrays.asList(serverIds);

    Query query = entityManager.createNamedQuery(AffinityGroup.QUERY_UPDATE_REMOVE_SPECIFIC_SERVERS);
    query.setParameter("serverIds", serverIdsList);

    query.executeUpdate();

    // Audit each changed affinity group assignment (is this too verbose?)
    for (Integer serverId : serverIdsList) {
        Server server = entityManager.find(Server.class, serverId);
        partitionEventManager.auditPartitionEvent(subject, PartitionEventType.SERVER_AFFINITY_GROUP_REMOVE,
                server.getName());//  www. ja v  a2  s . c  o m

    }
    // Now, request a cloud repartitioning due to the affinity group changes
    partitionEventManager.cloudPartitionEventRequest(subject, PartitionEventType.AFFINITY_GROUP_CHANGE,
            PartitionEventType.AGENT_AFFINITY_GROUP_REMOVE.name());

}