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

/**
 * @see io.apiman.manager.api.core.IStorage#deleteMembership(java.lang.String, java.lang.String, java.lang.String)
 */// w  w w.  j a va  2 s  .c o  m
@Override
public void deleteMembership(String userId, String roleId, String organizationId) throws StorageException {
    try {
        EntityManager entityManager = getActiveEntityManager();
        Query query = entityManager.createQuery(
                "DELETE FROM RoleMembershipBean m WHERE m.roleId = :roleId AND m.userId = :userId AND m.organizationId = :orgId");
        query.setParameter("roleId", roleId);
        query.setParameter("userId", userId);
        query.setParameter("orgId", organizationId);
        query.executeUpdate();
    } catch (Throwable t) {
        throw new StorageException(t);
    }
}

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

/**
 * @see org.opencms.db.I_CmsUserDriver#writeUser(org.opencms.db.CmsDbContext, org.opencms.file.CmsUser)
 *///  ww  w. j av  a  2 s  . c o  m
public void writeUser(CmsDbContext dbc, CmsUser user) throws CmsDataAccessException {

    // get the login attribute
    String att_login = (String) dbc.getAttribute(CmsDriverManager.ATTRIBUTE_LOGIN);

    // if the login attribute is set, do only update the last login information of this user
    // otherweise write the complete user data
    if (CmsStringUtil.isNotEmpty(att_login)) {
        try {
            Query q = m_sqlManager.createQuery(dbc, C_USERS_WRITE_2);
            // write data to database
            q.setParameter(1, Long.valueOf(user.getLastlogin()));
            q.setParameter(2, String.valueOf(user.getId().toString()));
            q.executeUpdate();
        } catch (PersistenceException e) {
            throw new CmsDataAccessException(Messages.get().container(Messages.ERR_JPA_PERSITENCE, e), e);
        }
    } else {
        try {
            Query q = m_sqlManager.createQuery(dbc, C_USERS_WRITE_6);
            // write data to database
            q.setParameter(1, user.getId().toString());
            @SuppressWarnings("unchecked")
            List<CmsDAOUsers> res = q.getResultList();

            for (CmsDAOUsers u : res) {
                u.setUserFirstName(m_sqlManager.validateEmpty(user.getFirstname()));
                u.setUserLastName(m_sqlManager.validateEmpty(user.getLastname()));
                u.setUserEmail(m_sqlManager.validateEmpty(user.getEmail()));
                u.setUserLastLogin(user.getLastlogin());
                u.setUserFlags(user.getFlags());
            }
        } catch (PersistenceException e) {
            throw new CmsDataAccessException(Messages.get().container(Messages.ERR_JPA_PERSITENCE, e), e);
        }
    }
    internalWriteUserInfos(dbc, user.getId(), user.getAdditionalInfo());
}

From source file:pl.datamatica.traccar.api.providers.UserProvider.java

private void removeUserResources(User user) throws Exception {

    DeviceGroupProvider deviceGroupProvider = new DeviceGroupProvider(em, user);
    GeoFenceProvider geoProvider = new GeoFenceProvider(em);
    geoProvider.setRequestUser(user);//  ww w  .  j  av a2  s.  co m

    //users
    user.setManagedUsers(Collections.EMPTY_SET);
    em.persist(user);

    Query query = em.createQuery("SELECT u FROM User u WHERE u.managedBy = :manager");
    query.setParameter("manager", user);
    for (User us : (List<User>) query.getResultList()) {
        us.setManagedBy(requestUser);
        logger.info("{} became manager of {}", requestUser.getLogin(), us.getLogin());
    }

    // devices
    user.setDevices(Collections.EMPTY_SET);
    em.persist(user);

    query = em.createQuery("SELECT d FROM Device d WHERE d.owner = :owner");
    query.setParameter("owner", user);
    for (Device dev : (List<Device>) query.getResultList()) {
        dev.setOwner(requestUser);
        logger.info("{} became owner of {}(id={})", requestUser.getLogin(), dev.getName(), dev.getId());
    }
    em.flush();

    // tracks
    RouteProvider rp = new RouteProvider(em, user);
    query = em.createQuery("SELECT r FROM Route r wHERE r.owner = :owner");
    query.setParameter("owner", user);
    for (Route r : (List<Route>) query.getResultList())
        rp.forceDeleteRoute(r);

    // geofences
    query = em.createQuery("SELECT g FROM GeoFence g WHERE :user in elements(g.users)");
    query.setParameter("user", user);
    List<GeoFence> gfs = query.getResultList();
    for (GeoFence geo : gfs) {
        if (geo.getOwner() == user) {
            geo.setUsers(new HashSet<>());
            geo.setOwner(null);
            em.flush();
            em.remove(geo);
        } else {
            Set<User> us = geo.getUsers();
            us.remove(user);
            geo.setUsers(us);
        }
    }
    em.flush();

    // groups
    for (Group gr : user.getGroups()) {
        Set<User> us = gr.getUsers();
        if (us == null)
            continue;
        if (us.size() == 1) {
            deviceGroupProvider.hardRemoveGroup(gr);
        } else {
            us.remove(user);
            gr.setUsers(us);
        }
    }

    // RulesAcceptances
    query = em.createQuery("DELETE FROM RulesAcceptance a WHERE a.id.user = :user");
    query.setParameter("user", user);
    query.executeUpdate();

    //BleDevices
    query = em.createQuery("DELETE FROM BleDevice bd where bd.owner = :user");
    query.setParameter("user", user);
    query.executeUpdate();

    //UserEvent
    query = em.createQuery("DELETE FROM UserEvent ue where ue.user = :user");
    query.setParameter("user", user);
    query.executeUpdate();
}

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

/**
 * Updates additional user info.<p>
 * @param dbc the current dbc//  w w  w . ja  v  a 2 s .c o m
 * @param userId the user id to add the user info for
 * @param key the name of the additional user info
 * @param value the value of the additional user info
 * @throws CmsDataAccessException if something goes wrong 
 */
protected void internalUpdateUserInfo(CmsDbContext dbc, CmsUUID userId, String key, Object value)
        throws CmsDataAccessException {

    try {
        Query q = m_sqlManager.createQuery(dbc, C_USERDATA_UPDATE_4);
        // write data to database
        q.setParameter(1, CmsDataTypeUtil.dataSerialize(value));
        q.setParameter(2, value.getClass().getName());
        q.setParameter(3, userId.toString());
        q.setParameter(4, key);
        q.executeUpdate();
    } catch (PersistenceException e) {
        throw new CmsDbSqlException(Messages.get().container(Messages.ERR_GENERIC_SQL_1, C_USERDATA_UPDATE_4),
                e);
    } catch (IOException e) {
        throw new CmsDbIoException(Messages.get().container(Messages.ERR_SERIALIZING_USER_DATA_1, userId), e);
    }
}

From source file:org.rhq.enterprise.server.resource.ResourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean bulkNamedQueryDeleteInNewTransaction(Subject subject, String namedQuery,
        List<Integer> resourceIds) {
    if (!authorizationManager.isOverlord(subject)) {
        throw new IllegalArgumentException("Only the overlord can execute arbitrary named query strings");
    }//  w w  w . j  av  a 2  s .  co m

    try {
        Query nativeQuery = entityManager.createNamedQuery(namedQuery);
        nativeQuery.setParameter("resourceIds", resourceIds);
        nativeQuery.executeUpdate();
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.error("Bulk named query delete error for '" + namedQuery + "' for " + resourceIds, t);
        } else {
            log.error("Bulk named query delete error for '" + namedQuery + "' for " + resourceIds + ": "
                    + t.getMessage());
        }
        return true; // had errors
    }
    return false;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public int deleteGroupPluginConfigurationUpdates(Subject subject, Integer resourceGroupId,
        Integer[] groupPluginConfigurationUpdateIds) {

    // TODO: use subject and resourceGroupId to perform security check

    if (authorizationManager.hasGroupPermission(subject, Permission.MODIFY_RESOURCE,
            resourceGroupId) == false) {
        log.error(subject + " attempted to delete " + groupPluginConfigurationUpdateIds.length
                + " group resource configuration updates for ResourceGroup[id" + resourceGroupId
                + "], but did not have the " + Permission.MODIFY_RESOURCE.name()
                + " permission for this group");
        return 0;
    }//w w  w.  j a  v  a  2 s.co m

    int removed = 0;
    for (Integer apcuId : groupPluginConfigurationUpdateIds) {
        /*
         * use this strategy instead of GroupPluginConfigurationUpdate.QUERY_DELETE_BY_ID because removing via
         * the entityManager will respect cascading rules, using a JPQL DELETE statement will not
         */
        try {
            // break the plugin configuration update links in order to preserve individual change history
            Query q = entityManager.createNamedQuery(PluginConfigurationUpdate.QUERY_DELETE_GROUP_UPDATE);
            q.setParameter("apcuId", apcuId);
            q.executeUpdate();

            GroupPluginConfigurationUpdate update = getGroupPluginConfigurationById(apcuId);
            entityManager.remove(update);
            removed++;
        } catch (Exception e) {
            log.error("Problem removing group plugin configuration update", e);
        }
    }

    return removed;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public int deleteGroupResourceConfigurationUpdates(Subject subject, Integer resourceGroupId,
        Integer[] groupResourceConfigurationUpdateIds) {

    if (authorizationManager.hasGroupPermission(subject, Permission.MODIFY_RESOURCE,
            resourceGroupId) == false) {
        log.error(subject + " attempted to delete " + groupResourceConfigurationUpdateIds.length
                + " group resource configuration updates for ResourceGroup[id" + resourceGroupId
                + "], but did not have the " + Permission.MODIFY_RESOURCE.name()
                + " permission for this group");
        return 0;
    }//ww w .  j  av a  2 s  . c  o m

    int removed = 0;
    for (Integer arcuId : groupResourceConfigurationUpdateIds) {
        /*
         * use this strategy instead of GroupResourceConfigurationUpdate.QUERY_DELETE_BY_ID because removing via
         * the entityManager will respect cascading rules, using a JPQL DELETE statement will not
         */
        try {
            // break the resource configuration update links in order to preserve individual change history
            Query q = entityManager.createNamedQuery(ResourceConfigurationUpdate.QUERY_DELETE_GROUP_UPDATE);
            q.setParameter("arcuId", arcuId);
            q.executeUpdate();

            GroupResourceConfigurationUpdate update = getGroupResourceConfigurationById(arcuId);
            entityManager.remove(update);
            removed++;
        } catch (Exception e) {
            log.error("Problem removing group resource configuration update", e);
        }
    }

    return removed;
}

From source file:org.rhq.enterprise.server.resource.ResourceManagerBean.java

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public boolean bulkNativeQueryDeleteInNewTransaction(Subject subject, String nativeQueryString,
        List<Integer> resourceIds) {
    if (!authorizationManager.isOverlord(subject)) {
        throw new IllegalArgumentException("Only the overlord can execute arbitrary native query strings");
    }//from w w  w .  ja v a 2s . c o  m

    try {
        Query nativeQuery = entityManager.createNativeQuery(nativeQueryString);
        nativeQuery.setParameter("resourceIds", resourceIds);
        nativeQuery.executeUpdate();
    } catch (Throwable t) {
        if (log.isDebugEnabled()) {
            log.error("Bulk native query delete error for '" + nativeQueryString + "' for " + resourceIds, t);
        } else {
            log.error("Bulk native query delete error for '" + nativeQueryString + "' for " + resourceIds + ": "
                    + t.getMessage());
        }
        return true; // had errors
    }
    return false;
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public void deleteProperties(int[] propertyIds) {
    if (propertyIds == null || propertyIds.length == 0) {
        return;//from w w w. j a v a2s  . co  m
    }

    Query propertiesQuery = entityManager.createNamedQuery(Property.QUERY_DELETE_BY_PROPERTY_IDS);
    propertiesQuery.setParameter("propertyIds", ArrayUtils.wrapInList(propertyIds));
    propertiesQuery.executeUpdate();
}

From source file:org.rhq.enterprise.server.configuration.ConfigurationManagerBean.java

public void deleteConfigurations(List<Integer> configurationIds) {
    if (configurationIds == null || configurationIds.size() == 0) {
        return;// w  w  w .jav a2s.co m
    }

    boolean supportsCascade = DatabaseTypeFactory.getDefaultDatabaseType().supportsSelfReferringCascade();
    if (supportsCascade == false) {
        Query breakPropertyRecursionQuery = entityManager
                .createNamedQuery(Configuration.QUERY_BREAK_PROPERTY_RECURSION_BY_CONFIGURATION_IDS);
        breakPropertyRecursionQuery.setParameter("configurationIds", configurationIds);
        breakPropertyRecursionQuery.executeUpdate();
    }

    Query rawConfigurationsQuery = entityManager
            .createNamedQuery(Configuration.QUERY_DELETE_RAW_CONFIGURATIONS_CONFIGURATION_IDS);
    Query configurationsQuery = entityManager
            .createNamedQuery(Configuration.QUERY_DELETE_CONFIGURATIONS_BY_CONFIGURATION_IDs);

    rawConfigurationsQuery.setParameter("configurationIds", configurationIds);
    configurationsQuery.setParameter("configurationIds", configurationIds);

    rawConfigurationsQuery.executeUpdate();
    configurationsQuery.executeUpdate(); // uses DB-level cascades to delete properties
}