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:pl.datamatica.traccar.api.providers.UserProvider.java

public void updateUserBleDevices(long id, List<BleDeviceDto> dtos) throws ProviderException {
    if (id != requestUser.getId())
        throw new ProviderException(Type.ACCESS_DENIED);
    if (!dtos.isEmpty()) {
        requestUser.setWasBleUser(true);
        requestUser.setHadAnyDevice(true);
    }//from  www .j  ava 2 s .c  om

    Query q = em.createQuery("DELETE FROM BleDevice bd where bd.owner = :user");
    q.setParameter("user", requestUser);
    q.executeUpdate();

    List<BleDevice> bled = new ArrayList<>();
    for (BleDeviceDto dto : dtos) {
        BleDevice bd = new BleDevice();
        bd.setModelName(dto.getModelName());
        bd.setCreationTimestamp(dto.getCreationTimestamp());
        bd.setPhoneModel(dto.getPhoneModel().toLowerCase());
        bd.setPhoneSystem(dto.getPhoneSystem().toLowerCase());
        bd.setOwner(requestUser);
        em.persist(bd);
        bled.add(bd);
    }
    requestUser.updateBleDevices(bled);
    em.persist(requestUser);
}

From source file:com.exp.tracker.services.impl.JpaSettlementService.java

@SuppressWarnings("unchecked")
@Transactional/*  w w  w. java  2s . c  o m*/
public Long createSettlement(SettlementBean sb, RequestContext ctx) {
    Long result = 0l;
    // create new settlement
    SettlementEntity se = new SettlementEntity();
    Query queryGetExpenses = null;
    queryGetExpenses = em.createNamedQuery("getUnsettledExpenses");
    queryGetExpenses.setParameter("startDate", sb.getStartDate());
    queryGetExpenses.setParameter("endDate", sb.getEndDate());
    Collection<ExpenseEntity> expenses = queryGetExpenses.getResultList();
    if (expenses.size() == 0) {
        ctx.getMessageContext()
                .addMessage(new MessageBuilder().warning().defaultText("No expenses to settle.").build());
        return 0l; // get out now
    }

    // calculate volume
    float volume = 0.0f;
    for (ExpenseEntity ee : expenses) {
        volume = volume + ee.getAmount();
    }
    // set volume
    se.setVolume(volume);
    se.setStartDate(sb.getStartDate());
    se.setEndDate(sb.getEndDate());
    Calendar cal = Calendar.getInstance();
    se.setCreatedDate(cal.getTime());
    se.setAccountManager(sb.getAccountManager());
    se.setSettlementCompleted(SettlementEntity.SETTLEMENT_NOT_COMPLETED);
    em.persist(se); // settlement created at root level
    // an indicator that we succeded
    result = se.getId();

    // get all users now
    Query queryGetUsers = em.createNamedQuery("getAllUsers");
    Query queryExpenseForUser = em.createNamedQuery("unsettledExpenseForUser");
    Query queryAmountPaidByUser = em.createNamedQuery("unsettledAmountPaidByUser");
    Collection<UserEntity> users = queryGetUsers.getResultList(); // user
    // list
    // obtained
    Set<UserSettlementEntity> usl = new HashSet<UserSettlementEntity>();
    for (UserEntity u : users) {
        boolean thisIsAnUser = false;
        for (AuthEntity ae : u.getAuthSet()) {
            if (ae.getAuthority().equalsIgnoreCase(RoleEntity.ROLE_USER)) {
                thisIsAnUser = true;
                break;
            }
        }

        UserSettlementEntity use = new UserSettlementEntity();
        use.setSettlement_id(se.getId());
        use.setSettlementFlag(UserSettlementEntity.SETTLEMENT_NOT_COMPLETED);
        // obtain expenses for user
        queryExpenseForUser.setParameter("startDate", sb.getStartDate());
        queryExpenseForUser.setParameter("endDate", sb.getEndDate());
        queryExpenseForUser.setParameter("userName", u.getUsername());
        Double expenseForUser = (Double) queryExpenseForUser.getSingleResult();
        if (null == expenseForUser) {
            expenseForUser = 0.0d;
        }
        // total share for this user
        use.setUserShare(Float.parseFloat(Double.toString(expenseForUser)));

        // obtain total paid by user
        queryAmountPaidByUser.setParameter("startDate", sb.getStartDate());
        queryAmountPaidByUser.setParameter("endDate", sb.getEndDate());
        queryAmountPaidByUser.setParameter("paidBy", u.getUsername());
        Double paidByUser = (Double) queryAmountPaidByUser.getSingleResult();

        if (null == paidByUser) {
            paidByUser = 0.0d;
        }
        // total paid by this user
        use.setUserPaid(Float.parseFloat(Double.toString(paidByUser)));
        //
        // set net amount - payable or receivable
        use.setAmount(Float.parseFloat(Double.toString(paidByUser))
                - Float.parseFloat(Double.toString(expenseForUser)));
        if (use.getAmount() == 0.0f) {
            // auto settled
            use.setSettlementFlag(UserSettlementEntity.SETTLEMENT_COMPLETED);
            use.setSettledDate(new Date());
        }
        use.setUserName(u.getUsername());
        if (thisIsAnUser || (expenseForUser > 0.0d)) {
            usl.add(use);
        }
    }
    se.setUserSettlementSet(usl);
    em.merge(se); // individual amounts merged

    // now update expenses
    Query queryAddSettlementId = null;
    queryAddSettlementId = em.createNamedQuery("addSettlementId");
    queryAddSettlementId.setParameter("startDate", sb.getStartDate());
    queryAddSettlementId.setParameter("endDate", sb.getEndDate());
    queryAddSettlementId.setParameter("settlementId", se.getId());
    queryAddSettlementId.executeUpdate(); // expenses updated
    ctx.getMessageContext()
            .addMessage(new MessageBuilder().info().defaultText("Settlement was created succesfuly.").build());
    return result;
}

From source file:org.rhq.enterprise.server.event.EventManagerBean.java

public int deleteEventsForContext(Subject subject, EntityContext context, List<Integer> eventIds) {
    if (eventIds == null || eventIds.size() == 0) {
        return 0; // nothing to delete, thus 0 were deleted
    }//from  w ww. ja v  a  2  s .  c o m

    if (context.type == EntityContext.Type.Resource) {
        if (authorizationManager.hasResourcePermission(subject, Permission.MANAGE_EVENTS,
                context.resourceId) == false) {
            throw new PermissionException("User [" + subject.getName()
                    + "] does not have permissions to delete events for resource[id=" + context.resourceId
                    + "]");
        }
    } else if (context.type == EntityContext.Type.ResourceGroup) {
        if (authorizationManager.hasGroupPermission(subject, Permission.MANAGE_EVENTS,
                context.groupId) == false) {
            throw new PermissionException("User [" + subject.getName()
                    + "] does not have permissions to delete events for resourceGroup[id=" + context.groupId
                    + "]");
        }
    } else if (context.type == EntityContext.Type.AutoGroup) {
        if (authorizationManager.canViewAutoGroup(subject, context.parentResourceId,
                context.resourceTypeId) == false) {
            throw new PermissionException("User [" + subject.getName()
                    + "] does not have permission to view event history for autoGroup[parentResourceId="
                    + context.parentResourceId + ", resourceTypeId=" + context.resourceTypeId + "]");
        }
    }

    Query q = entityManager.createNamedQuery(Event.DELETE_BY_EVENT_IDS);
    q.setParameter("eventIds", eventIds);
    int deletedCount = q.executeUpdate();

    return deletedCount;
}

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

protected void clearDayHits() throws WebloggerException {
    Query query = strategy.getNamedUpdate("WeblogReferrer.clearDayHits");
    query.executeUpdate();
}

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

private void removeUserSettings(User user) throws Exception {
    Query query;

    query = em.createQuery("DELETE FROM NotificationSettings WHERE user = ?");
    query.setParameter(1, user);//from   ww w  .  j ava 2s.c  om
    query.executeUpdate();

    //Remove user data from table users_notifications
    user.setNotificationEvents(Collections.EMPTY_SET);

    //Remove user data from table users_mobilenotifications        
    user.setMobileNotificationSettings(Collections.EMPTY_MAP);

    em.persist(user);

    query = em.createQuery("DELETE FROM UIStateEntry WHERE user = ?");
    query.setParameter(1, user);
    query.executeUpdate();

    query = em.createQuery("DELETE FROM UserDeviceStatus uds WHERE uds.id.user = ?");
    query.setParameter(1, user);
    query.executeUpdate();

    query = em.createQuery("DELETE FROM UserSession us WHERE us.userId = ?");
    query.setParameter(1, user.getId());
    query.executeUpdate();
}

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

/**
 * Clear referrer dayhits and remove referrers without excerpts.
 *///w ww.  j  a  v  a2 s  . c o  m
public void clearReferrers() throws WebloggerException {
    clearDayHits();
    Query q = strategy.getNamedUpdate("WeblogReferrer.removeByNullOrEmptyExcerpt");
    q.executeUpdate();
}

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

public int deletePrivateMessages(List<Long> privateMessageIds) {
    try {/*from w  ww  .  j av  a2  s . c o m*/
        Query query = em.createNamedQuery("deletePrivateMessages");
        query.setParameter("privateMessageIds", privateMessageIds);
        return query.executeUpdate();
    } catch (Exception e) {
        log.error("[deletePrivateMessages]", e);
    }
    return -1;
}

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

@Override
public void markRecordsForComputeACLEntries(RecordCollection collection) {
    // Bug in JTA prevents us from doing a single update with connectorInstance.recordCollection
    for (ConnectorInstance connectorInstance : collection.getConnectorInstances()) {
        String ql = "UPDATE Record SET computeACLEntries=true WHERE connectorInstance = :connectorInstance";
        Query query = this.getEntityManager().createQuery(ql);
        query.setParameter("connectorInstance", connectorInstance);
        query.executeUpdate();
    }/*  w  w w .j a v a2 s .  c  o m*/
    markRecordsForUpdateIndex(collection);
}

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

@Override
public void markRecordsForDeletion(RecordCollection collection) {
    // Bug in JTA prevents us from doing a single update with connectorInstance.recordCollection
    for (ConnectorInstance connectorInstance : collection.getConnectorInstances()) {
        String ql = "UPDATE Record SET deleted=true WHERE connectorInstance = :connectorInstance";
        Query query = this.getEntityManager().createQuery(ql);
        query.setParameter("connectorInstance", connectorInstance);
        query.executeUpdate();
    }//from  w w  w .  j av  a  2  s  . c o m
    IndexingManager indexingManager = IndexingManager.get(collection);
    if (!indexingManager.isActive()) {
        indexingManager.startIndexing(true);
    }
}

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

@Override
public void markRecordsForUpdateIndex(RecordCollection collection) {
    // Bug in JTA prevents us from doing a single update with connectorInstance.recordCollection
    for (ConnectorInstance connectorInstance : collection.getConnectorInstances()) {
        String ql = "UPDATE Record SET updateIndex=true WHERE connectorInstance = :connectorInstance";
        Query query = this.getEntityManager().createQuery(ql);
        query.setParameter("connectorInstance", connectorInstance);
        query.executeUpdate();
    }/*from  ww  w.  j  a  v a2  s.c om*/
    IndexingManager indexingManager = IndexingManager.get(collection);
    if (!indexingManager.isActive()) {
        indexingManager.startIndexing(true);
    } else {
        indexingManager.reindexAll();
    }
}