Example usage for javax.persistence TypedQuery executeUpdate

List of usage examples for javax.persistence TypedQuery executeUpdate

Introduction

In this page you can find the example usage for javax.persistence TypedQuery executeUpdate.

Prototype

int executeUpdate();

Source Link

Document

Execute an update or delete statement.

Usage

From source file:eu.europa.ec.fisheries.uvms.spatial.service.dao.UserAreaDao.java

/**
 * <p>Update Start date and End date for user areas if the user is having scope <code><B>MANAGE_ANY_USER_AREA</B></code>
 * <p><code>StartDate</code> and <code>EndDate</code> can be NULL or Empty or a Valid Date</p>
 *
 * @param startDate Start Date//  ww w .  j  a v a  2  s .c  o m
 * @param endDate End Date
 * @param type Area Type
 * @exception ServiceException Exception is Date cannot be updated
 *
 * @see UserAreaDao#updateUserAreasForUser(String, Date, Date, String)
 */
public void updateUserAreasForUserAndScope(Date startDate, Date endDate, String type) throws ServiceException {
    TypedQuery query = (TypedQuery) getEntityManager()
            .createNamedQuery(UserAreasEntity.UPDATE_USERAREA_FORUSER_AND_SCOPE);
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    query.setParameter("type", type);
    query.executeUpdate();
}

From source file:eu.europa.ec.fisheries.uvms.spatial.service.dao.UserAreaDao.java

/**
 * <p>Update Start date and End date for user areas those are created by the user</p>
 * <p><code>StartDate</code> and <code>EndDate</code> can be NULL or Empty or a Valid Date</p>
 *
 * @param remoteUser User Name/*from w  ww . j a v  a  2 s . c  om*/
 * @param startDate Start Date
 * @param endDate End Date
 * @param type Area Type
 * @throws ServiceException Exception is Date cannot be updated
 *
 * @see UserAreaDao#updateUserAreasForUserAndScope(Date, Date, String)
 */
public void updateUserAreasForUser(String remoteUser, Date startDate, Date endDate, String type)
        throws ServiceException {
    TypedQuery query = (TypedQuery) getEntityManager()
            .createNamedQuery(UserAreasEntity.UPDATE_USERAREA_FORUSER);
    query.setParameter("startDate", startDate);
    query.setParameter("endDate", endDate);
    query.setParameter("userName", remoteUser);
    query.setParameter("type", type);
    query.executeUpdate();
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}// w ww. j  a v a 2 s  .c  om
 */
@Override
public <T extends BaseEntity> int deleteByJpaNamedQuery(CrudDTO<T> crudDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        TypedQuery<T> typedQuery = em.createNamedQuery(crudDTO.getNamedQuery(), crudDTO.getEntity());
        JpaUtil.bindQueryParams(typedQuery, crudDTO.getPosParams());
        int rowsDeleted = typedQuery.executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteByJpaNamedQuery: No. of rows deleted: [{}]", rowsDeleted);
        return rowsDeleted;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:com.clustercontrol.notify.monitor.util.QueryUtil.java

public static int updateEventLogFlgByFilter(String[] facilityIds, Integer[] priorityList, Long outputFromDate,
        Long outputToDate, Long generationFromDate, Long generationToDate, String monitorId,
        String monitorDetailId, String application, String message, Integer confirmFlg, String confirmUser,
        String comment, String commentUser, Integer confirmType, Long confirmDate, Boolean collectGraphFlg) {

    HinemosEntityManager em = new JpaTransactionManager().getEntityManager();

    // ??????????
    String notInclude = "NOT:";

    // ???????//from   w w w.jav a2 s.c  om
    Integer selectConfirmFlg = null;
    if (confirmType == ConfirmConstant.TYPE_CONFIRMED) {
        selectConfirmFlg = ConfirmConstant.TYPE_UNCONFIRMED;
    } else if (confirmType == ConfirmConstant.TYPE_UNCONFIRMED) {
        selectConfirmFlg = ConfirmConstant.TYPE_CONFIRMED;
    }

    // SQL?
    StringBuffer sbJpql = new StringBuffer();
    sbJpql.append(
            "UPDATE EventLogEntity a SET a.confirmFlg = :confirmFlg, a.confirmDate = :confirmDate, a.confirmUser = :confirmUser");
    sbJpql.append(" WHERE true = true");

    // ID
    if (facilityIds != null && facilityIds.length > 0) {
        sbJpql.append(" AND a.id.facilityId IN ("
                + HinemosEntityManager.getParamNameString("facilityId", facilityIds) + ")");
    }
    // ??
    if (priorityList != null && priorityList.length > 0
            && priorityList.length != PriorityConstant.PRIORITY_LIST.length) {
        sbJpql.append(" AND a.priority IN ("
                + HinemosEntityManager.getParamNameString("priority", new String[priorityList.length]) + ")");
    }
    // ?
    if (outputFromDate != null) {
        sbJpql.append(" AND a.id.outputDate >= :outputFromDate");
    }
    // ?
    if (outputToDate != null) {
        sbJpql.append(" AND a.id.outputDate <= :outputToDate ");
    }
    // 
    if (generationFromDate != null) {
        sbJpql.append(" AND a.generationDate >= :generationFromDate ");
    }
    // 
    if (generationToDate != null) {
        sbJpql.append(" AND a.generationDate <= :generationToDate ");
    }
    // ID
    if (monitorId != null && !"".equals(monitorId)) {
        if (!monitorId.startsWith(notInclude)) {
            sbJpql.append(" AND a.id.monitorId like :monitorId");
        } else {
            sbJpql.append(" AND a.id.monitorId not like :monitorId");
        }
    }
    // 
    if (monitorDetailId != null && !"".equals(monitorDetailId)) {
        if (!monitorDetailId.startsWith(notInclude)) {
            sbJpql.append(" AND a.id.monitorDetailId like :monitorDetailId");
        } else {
            sbJpql.append(" AND a.id.monitorDetailId not like :monitorDetailId");
        }
    }
    // 
    if (application != null && !"".equals(application)) {
        if (!application.startsWith(notInclude)) {
            sbJpql.append(" AND a.application like :application");
        } else {
            sbJpql.append(" AND a.application not like :application");
        }
    }
    // 
    if (message != null && !"".equals(message)) {
        if (!message.startsWith(notInclude)) {
            sbJpql.append(" AND a.message like :message");
        } else {
            sbJpql.append(" AND a.message not like :message");
        }
    }
    // 
    if (comment != null && !"".equals(comment)) {
        if (!comment.startsWith(notInclude)) {
            sbJpql.append(" AND a.comment like :comment");
        } else {
            sbJpql.append(" AND a.comment not like :comment");
        }
    }
    //
    if (commentUser != null && !"".equals(commentUser)) {
        if (!commentUser.startsWith(notInclude)) {
            sbJpql.append(" AND a.commentUser like :commentUser");
        } else {
            sbJpql.append(" AND a.commentUser not like :commentUser");
        }
    }
    // ?
    if (selectConfirmFlg != null) {
        sbJpql.append(" AND a.confirmFlg = :selectConfirmFlg ");
    }

    TypedQuery<Integer> query = em
            .createQuery(sbJpql.toString(), Integer.class, EventLogEntity.class, ObjectPrivilegeMode.MODIFY)
            .setParameter("confirmFlg", confirmFlg).setParameter("confirmDate", confirmDate)
            .setParameter("confirmUser", confirmUser);
    // ID
    if (facilityIds != null && facilityIds.length > 0) {
        query = HinemosEntityManager.appendParam(query, "facilityId", facilityIds);
    }
    // ??
    if (priorityList != null && priorityList.length > 0
            && priorityList.length != PriorityConstant.PRIORITY_LIST.length) {
        int count = priorityList.length;
        if (count > 0) {
            for (int i = 0; i < count; i++) {
                query = query.setParameter("priority" + i, priorityList[i]);
            }
        }
    }
    // ?
    if (outputFromDate != null) {
        query.setParameter("outputFromDate", outputFromDate);
    }
    // ?
    if (outputToDate != null) {
        query.setParameter("outputToDate", outputToDate);
    }
    // 
    if (generationFromDate != null) {
        query.setParameter("generationFromDate", generationFromDate);
    }
    // 
    if (generationToDate != null) {
        query.setParameter("generationToDate", generationToDate);
    }
    // ID
    if (monitorId != null && !"".equals(monitorId)) {
        if (!monitorId.startsWith(notInclude)) {
            query = query.setParameter("monitorId", monitorId);
        } else {
            query = query.setParameter("monitorId", monitorId.substring(notInclude.length()));
        }
    }
    // 
    if (monitorDetailId != null && !"".equals(monitorDetailId)) {
        if (!monitorDetailId.startsWith(notInclude)) {
            query = query.setParameter("monitorDetailId", monitorDetailId);
        } else {
            query = query.setParameter("monitorDetailId", monitorDetailId.substring(notInclude.length()));
        }
    }
    // 
    if (application != null && !"".equals(application)) {
        if (!application.startsWith(notInclude)) {
            query = query.setParameter("application", application);
        } else {
            query = query.setParameter("application", application.substring(notInclude.length()));
        }
    }
    // 
    if (message != null && !"".equals(message)) {
        if (!message.startsWith(notInclude)) {
            query = query.setParameter("message", message);
        } else {
            query = query.setParameter("message", message.substring(notInclude.length()));
        }
    }
    //
    if (comment != null && !"".equals(comment)) {
        if (!comment.startsWith(notInclude)) {
            query = query.setParameter("comment", comment);
        } else {
            query = query.setParameter("comment", comment.substring(notInclude.length()));
        }
    }
    //
    if (commentUser != null && !"".equals(commentUser)) {
        if (!commentUser.startsWith(notInclude)) {
            query = query.setParameter("commentUser", commentUser);
        } else {
            query = query.setParameter("commentUser", commentUser.substring(notInclude.length()));
        }
    }
    // ?
    if (selectConfirmFlg != null) {
        query.setParameter("selectConfirmFlg", selectConfirmFlg);
    }
    // 
    if (collectGraphFlg != null) {
        query.setParameter("collectGraphFlg", collectGraphFlg);
    }

    return query.executeUpdate();
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Removes alert history and current alerts for the specified alert defintiion
 * ID. This will invoke {@link EntityManager#clear()} when completed since the
 * JPQL statement will remove entries without going through the EM.
 *
 * @param definitionId/* w w  w  . j  a  v a2s .c  om*/
 *          the ID of the definition to remove.
 */
@Transactional
public void removeByDefinitionId(long definitionId) {
    EntityManager entityManager = m_entityManagerProvider.get();
    TypedQuery<AlertCurrentEntity> currentQuery = entityManager
            .createNamedQuery("AlertCurrentEntity.removeByDefinitionId", AlertCurrentEntity.class);

    currentQuery.setParameter("definitionId", definitionId);
    currentQuery.executeUpdate();

    TypedQuery<AlertHistoryEntity> historyQuery = entityManager
            .createNamedQuery("AlertHistoryEntity.removeByDefinitionId", AlertHistoryEntity.class);

    historyQuery.setParameter("definitionId", definitionId);
    historyQuery.executeUpdate();

    entityManager.clear();

    // if caching is enabled, invalidate the cache to force the latest values
    // back from the DB
    if (m_configuration.isAlertCacheEnabled()) {
        m_currentAlertCache.invalidateAll();
    }
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Remove a current alert whose history entry matches the specfied ID.
 *
 * @param   historyId the ID of the history entry.
 * @return  the number of alerts removed.
 *//*  w  w  w .j a  va 2 s  .c  o  m*/
@Transactional
public int removeCurrentByHistoryId(long historyId) {
    TypedQuery<AlertCurrentEntity> query = m_entityManagerProvider.get()
            .createNamedQuery("AlertCurrentEntity.removeByHistoryId", AlertCurrentEntity.class);

    query.setParameter("historyId", historyId);
    int rowsRemoved = query.executeUpdate();

    // if caching is enabled, invalidate the cache to force the latest values
    // back from the DB
    if (m_configuration.isAlertCacheEnabled()) {
        m_currentAlertCache.invalidateAll();
    }

    return rowsRemoved;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Deletes AlertNotice records in relation with AlertHistory entries older than the given date.
 *
 * @param clusterId        the identifier of the cluster the AlertNotices belong to
 * @param beforeDateMillis the date in milliseconds the
 * @return a long representing the number of affected (deleted) records
 *//*  w  w w. jav a2 s.c om*/
@Transactional
private int cleanAlertNoticesForClusterBeforeDate(Long clusterId, long beforeDateMillis) {
    LOG.info("Deleting AlertNotice entities before date " + new Date(beforeDateMillis));
    EntityManager entityManager = m_entityManagerProvider.get();
    List<Integer> ids = findAllAlertHistoryIdsBeforeDate(clusterId, beforeDateMillis);
    int affectedRows = 0;
    // Batch delete
    TypedQuery<AlertNoticeEntity> noticeQuery = entityManager
            .createNamedQuery("AlertNoticeEntity.removeByHistoryIds", AlertNoticeEntity.class);
    if (ids != null && !ids.isEmpty()) {
        for (int i = 0; i < ids.size(); i += BATCH_SIZE) {
            int endIndex = (i + BATCH_SIZE) > ids.size() ? ids.size() : (i + BATCH_SIZE);
            List<Integer> idsSubList = ids.subList(i, endIndex);
            LOG.info("Deleting AlertNotice entity batch with history ids: " + idsSubList.get(0) + " - "
                    + idsSubList.get(idsSubList.size() - 1));
            noticeQuery.setParameter("historyIds", idsSubList);
            affectedRows += noticeQuery.executeUpdate();
        }
    }

    return affectedRows;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Deletes AlertCurrent records in relation with AlertHistory entries older than the given date.
 *
 * @param clusterId        the identifier of the cluster the AlertCurrents belong to
 * @param beforeDateMillis the date in milliseconds the
 * @return a long representing the number of affected (deleted) records
 *//*ww  w .  j  av  a 2s.  c om*/
@Transactional
private int cleanAlertCurrentsForClusterBeforeDate(long clusterId, long beforeDateMillis) {
    LOG.info("Deleting AlertCurrent entities before date " + new Date(beforeDateMillis));
    EntityManager entityManager = m_entityManagerProvider.get();
    List<Integer> ids = findAllAlertHistoryIdsBeforeDate(clusterId, beforeDateMillis);
    int affectedRows = 0;
    TypedQuery<AlertCurrentEntity> currentQuery = entityManager
            .createNamedQuery("AlertCurrentEntity.removeByHistoryIds", AlertCurrentEntity.class);
    if (ids != null && !ids.isEmpty()) {
        for (int i = 0; i < ids.size(); i += BATCH_SIZE) {
            int endIndex = (i + BATCH_SIZE) > ids.size() ? ids.size() : (i + BATCH_SIZE);
            List<Integer> idsSubList = ids.subList(i, endIndex);
            LOG.info("Deleting AlertCurrent entity batch with history ids: " + idsSubList.get(0) + " - "
                    + idsSubList.get(idsSubList.size() - 1));
            currentQuery.setParameter("historyIds", ids.subList(i, endIndex));
            affectedRows += currentQuery.executeUpdate();
        }
    }

    return affectedRows;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Utility method for executing update or delete named queries having as input parameters the cluster id and a timestamp.
 *
 * @param namedQuery the named query to be executed
 * @param entityType the type of the entity
 * @param clusterId  the cluster identifier
 * @param timestamp  timestamp//  w  ww.ja  va2  s.  com
 * @return the number of rows affected by the query execution.
 */
private int executeQuery(String namedQuery, Class entityType, long clusterId, long timestamp) {
    LOG.info("Starting: Delete/update entries older than [ {} ] for entity [{}]", timestamp, entityType);
    TypedQuery query = m_entityManagerProvider.get().createNamedQuery(namedQuery, entityType);

    query.setParameter("clusterId", clusterId);
    query.setParameter("beforeDate", timestamp);

    int affectedRows = query.executeUpdate();

    m_entityManagerProvider.get().flush();
    m_entityManagerProvider.get().clear();

    LOG.info(
            "Completed: Delete/update entries older than [ {} ] for entity: [{}]. Number of entities deleted: [{}]",
            timestamp, entityType, affectedRows);

    return affectedRows;
}

From source file:org.apache.rave.portal.repository.impl.JpaWidgetRepository.java

/**
 * Delete all Widget Comments for a userId
 *
 * @param userId/*from w w w .j  a  va 2  s .com*/
 * @return count of comments deleted
 */
@Override
public int deleteAllWidgetComments(String userId) {
    TypedQuery<JpaWidgetComment> query = manager.createNamedQuery(JpaWidgetComment.DELETE_ALL_BY_USER,
            JpaWidgetComment.class);
    query.setParameter("userId", userId);
    return query.executeUpdate();
}