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.juddi.api.impl.JUDDIApiImpl.java

/**
 * Deletes publisher(s) from the persistence layer. This method is
 * specific to jUDDI. Administrative privilege required.
 *
 * @param body/*from w ww  .  j a  v a 2  s  . co  m*/
 * @throws DispositionReportFaultMessage
 */
public void deletePublisher(DeletePublisher body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

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

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

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

            //get an authtoken for this publisher so that we can get its registeredInfo
            UDDISecurityImpl security = new UDDISecurityImpl();
            AuthToken authToken = security.getAuthToken(entityKey);

            GetRegisteredInfo r = new GetRegisteredInfo();
            r.setAuthInfo(authToken.getAuthInfo());
            r.setInfoSelection(InfoSelection.ALL);

            log.info("removing all businesses owned by publisher " + entityKey + ".");
            UDDIPublicationImpl publish = new UDDIPublicationImpl();
            RegisteredInfo registeredInfo = publish.getRegisteredInfo(r);
            BusinessInfos businessInfos = registeredInfo.getBusinessInfos();
            if (businessInfos != null && businessInfos.getBusinessInfo() != null) {
                Iterator<BusinessInfo> iter = businessInfos.getBusinessInfo().iterator();
                while (iter.hasNext()) {
                    BusinessInfo businessInfo = iter.next();
                    Object business = em.find(org.apache.juddi.model.BusinessEntity.class,
                            businessInfo.getBusinessKey());
                    em.remove(business);
                }
            }

            log.info("mark all tmodels for publisher " + entityKey + " as deleted.");
            TModelInfos tmodelInfos = registeredInfo.getTModelInfos();
            if (tmodelInfos != null && tmodelInfos.getTModelInfo() != null) {
                Iterator<TModelInfo> iter = tmodelInfos.getTModelInfo().iterator();
                while (iter.hasNext()) {
                    TModelInfo tModelInfo = iter.next();
                    Tmodel tmodel = (Tmodel) em.find(org.apache.juddi.model.Tmodel.class,
                            tModelInfo.getTModelKey());
                    tmodel.setDeleted(true);
                    em.persist(tmodel);
                }
            }
            log.info("remove all persisted AuthTokens for publisher " + entityKey + ".");
            Query q1 = em
                    .createQuery("DELETE FROM AuthToken auth WHERE auth.authorizedName = '" + entityKey + "'");
            q1.executeUpdate();

            log.info("removing publisher " + entityKey + ".");
            //delete the publisher
            em.remove(obj);
        }

        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

From source file:org.apache.oozie.service.JPAService.java

/**
 * Execute an UPDATE query//  w  w w  . j av  a 2s .c  om
 * @param namedQueryName the name of query to be executed
 * @param query query instance to be executed
 * @param em Entity Manager
 * @return Integer that query returns, which corresponds to the number of rows updated
 * @throws JPAExecutorException
 */
public int executeUpdate(String namedQueryName, Query query, EntityManager em) throws JPAExecutorException {
    Instrumentation.Cron cron = new Instrumentation.Cron();
    try {

        LOG.trace("Executing Update/Delete Query [{0}]", namedQueryName);
        if (instr != null) {
            instr.incr(INSTRUMENTATION_GROUP_JPA, namedQueryName, 1);
        }
        cron.start();
        em.getTransaction().begin();
        int ret = query.executeUpdate();
        if (em.getTransaction().isActive()) {
            if (FaultInjection.isActive("org.apache.oozie.command.SkipCommitFaultInjection")) {
                throw new RuntimeException("Skipping Commit for Failover Testing");
            }
            em.getTransaction().commit();
        }
        return ret;
    } catch (PersistenceException e) {
        throw new JPAExecutorException(ErrorCode.E0603, e);
    } finally {
        processFinally(em, cron, namedQueryName, true);
    }
}

From source file:org.kuali.mobility.push.dao.DeviceDaoImpl.java

@Transactional
public boolean removeAllDevicesBefore(Timestamp ts) {
    boolean result = true;

    Query query = entityManager.createQuery("select d from Device d where d.postedTimestamp < :ts");
    query.setParameter("ts", ts);
    List<Device> devices = query.getResultList();
    LOG.info("****** Found " + devices.size() + " devices registered or updated before " + ts);

    query = entityManager.createQuery("delete from Device where postedTimestamp < :ts");
    query.setParameter("ts", ts);
    result = (query.executeUpdate() > 0) ? true : false;

    LOG.info("****** Deleted " + result + " devices registered or updated before " + ts);
    return result;
}

From source file:org.tolven.analysis.bean.SnapshotBean.java

/**
 * This function deletes all patients in the echr:patients:cohorts:current list,
 * on any change in the cohort properties.
 *//*from   w  ww .ja  v  a 2  s .  c  o m*/
@Override
public void deletePatientCohortList(Account account, String analysisType) {
    Query query = em.createQuery("update  MenuData md set md.deleted=TRUE WHERE "
            + "md.account.id = :account and  md.path LIKE '%:cohorts:current%' and md.string01 = :analysisType");
    query.setParameter("account", account.getId());
    query.setParameter("analysisType", analysisType);
    query.executeUpdate();
}

From source file:org.exoplatform.social.addons.storage.RDBMSIdentityStorageImpl.java

/**
 * This method is introduced to clean totally identity from database
 * It's used in unit test/*from   ww w. ja  va  2 s.c  o  m*/
 * @param identity the Identity
 */
@ExoTransactional
public void removeIdentity(Identity identity) {
    long id = EntityConverterUtils.parseId(identity.getId());
    String username = identity.getRemoteId();
    String provider = identity.getProviderId();

    IdentityEntity entity = getIdentityDAO().find(id);

    EntityManager em = CommonsUtils.getService(EntityManagerService.class).getEntityManager();
    Query query;

    // Delete all connection
    query = em.createNamedQuery("SocConnection.deleteConnectionByIdentity");
    query.setParameter("identityId", id);
    query.executeUpdate();

    if (OrganizationIdentityProvider.NAME.equals(provider)) {
        // Delete space-member
        query = em.createNamedQuery("SpaceMember.deleteByUsername");
        query.setParameter("username", username);
        query.executeUpdate();
    }

    if (entity != null) {
        getIdentityDAO().delete(entity);
    }
}

From source file:org.exoplatform.social.addons.storage.RDBMSIdentityStorageImpl.java

/**
 * Hard delete an identity from JCR// w w  w . j a  va  2s  .  c  om
 *
 * @param identity the identity to be deleted
 * @throws IdentityStorageException if has any error
 */
@ExoTransactional
public void hardDeleteIdentity(final Identity identity) throws IdentityStorageException {
    long id = EntityConverterUtils.parseId(identity.getId());
    String username = identity.getRemoteId();
    String provider = identity.getProviderId();

    IdentityEntity entity = getIdentityDAO().find(id);
    if (entity != null) {
        entity.setDeleted(true);
        getIdentityDAO().update(entity);
    }

    if (entity.getAvatarFileId() != null && entity.getAvatarFileId() > 0) {
        fileService.deleteFile(entity.getAvatarFileId());
    }

    EntityManager em = CommonsUtils.getService(EntityManagerService.class).getEntityManager();
    Query query;

    // Delete all connection
    query = em.createNamedQuery("SocConnection.deleteConnectionByIdentity");
    query.setParameter("identityId", id);
    query.executeUpdate();

    if (OrganizationIdentityProvider.NAME.equals(provider)) {
        // Delete space-member
        query = em.createNamedQuery("SpaceMember.deleteByUsername");
        query.setParameter("username", username);
        query.executeUpdate();
    }
}

From source file:org.rhq.enterprise.server.plugin.ServerPluginManagerBean.java

@RequiredPermission(Permission.MANAGE_SETTINGS)
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void setServerPluginEnabledFlag(Subject subject, int pluginId, boolean enabled) throws Exception {
    Query q = entityManager.createNamedQuery(ServerPlugin.UPDATE_PLUGIN_ENABLED_BY_ID);
    q.setParameter("id", pluginId);
    q.setParameter("enabled", Boolean.valueOf(enabled));
    q.executeUpdate();
    log.info((enabled ? "Enabling" : "Disabling") + " server plugin [" + pluginId + "]");
    return;// w ww  .ja va 2  s  .c  om
}

From source file:com.doculibre.constellio.services.RecordServicesImpl.java

@Override
public void deleteAutomaticRecordTags(RecordCollection collection, Date newStartTaggingDate) {
    int attempts = 0;
    while (true) {
        try {// ww w  .j  ava  2 s  . co m
            String sqlTag;
            if (newStartTaggingDate == null) {
                sqlTag = "DELETE FROM RecordTag WHERE manual=? AND record_id IN"
                        + " (SELECT r.id FROM Record r, ConnectorInstance ci, RecordCollection rc"
                        + " WHERE r.connectorInstance_id=ci.id AND ci.recordCollection_id=rc.id AND rc.id=?)";
            } else {
                sqlTag = "DELETE FROM RecordTag WHERE manual=? AND record_id IN"
                        + " (SELECT r.id FROM Record r, ConnectorInstance ci, RecordCollection rc "
                        + "WHERE r.connectorInstance_id=ci.id AND ci.recordCollection_id=rc.id AND rc.id=? AND"
                        + " (r.lastAutomaticTagging > ? OR r.lastAutomaticTagging IS NULL))";
            }
            Query tagQuery = getEntityManager().createNativeQuery(sqlTag);
            tagQuery.setParameter(1, Boolean.FALSE);
            tagQuery.setParameter(2, collection.getId());
            if (newStartTaggingDate != null) {
                tagQuery.setParameter(3, newStartTaggingDate);
            }
            tagQuery.executeUpdate();

            String sqlRecord;
            if (newStartTaggingDate == null) {
                sqlRecord = "UPDATE Record r SET r.lastAutomaticTagging = null WHERE connectorInstance_id IN"
                        + " (SELECT ci.id FROM ConnectorInstance ci, RecordCollection rc WHERE ci.recordCollection_id=rc.id AND rc.id=?)";
            } else {
                sqlRecord = "UPDATE Record r SET r.lastAutomaticTagging = null WHERE connectorInstance_id IN"
                        + " (SELECT ci.id FROM ConnectorInstance ci, RecordCollection rc WHERE ci.recordCollection_id=rc.id AND"
                        + " rc.id=?) AND (r.lastAutomaticTagging > ? OR r.lastAutomaticTagging IS NULL)";
            }
            Query recordQuery = getEntityManager().createNativeQuery(sqlRecord);
            recordQuery.setParameter(1, collection.getId());
            if (newStartTaggingDate != null) {
                recordQuery.setParameter(2, newStartTaggingDate);
            }
            recordQuery.executeUpdate();
            break;
        } catch (PessimisticLockException e) {
            attempts++;
            if (attempts > 100) {
                throw e;
            }
        }
    }
}

From source file:org.tolven.analysis.bean.SnapshotBean.java

/**
 * This function deletes all patients in the echr:analysis:cohorts:all list,
 * on any change in the cohort properties.
 *///from   w w w .  j a va  2 s.  c om
@Override
public void deleteAnalysisCohortList(Account account, String analysisType) {
    Query query = em.createQuery("update  MenuData md set md.deleted=TRUE WHERE "
            + "md.account.id = :account and  md.string01 =:analysisType and md.path LIKE '%echr:analysis:cohorts:all-%'");
    query.setParameter("account", account.getId());
    query.setParameter("analysisType", analysisType);
    query.executeUpdate();
}

From source file:org.tolven.analysis.bean.SnapshotBean.java

/**
 * This function deletes the patients (It is generated manually when there is null cohort)
 * in the echr:analysis:cohorts:all list.
 * @author Pinky//from   w ww.ja v  a  2 s .co m
 * Created on 09/28/2010
 */
@Override
public void deleteFalseAnalysisCohortList(Account account, String analysisType) {
    Query query = em.createQuery("update  MenuData md set md.deleted=TRUE WHERE "
            + "md.account.id = :account and  md.string08 =:analysisType and md.path LIKE '%echr:analysis:cohorts:all-%'");
    query.setParameter("account", account.getId());
    query.setParameter("analysisType", analysisType);
    query.executeUpdate();
}