Example usage for javax.persistence.criteria CriteriaBuilder createCriteriaDelete

List of usage examples for javax.persistence.criteria CriteriaBuilder createCriteriaDelete

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder createCriteriaDelete.

Prototype

<T> CriteriaDelete<T> createCriteriaDelete(Class<T> targetEntity);

Source Link

Document

Create a CriteriaDelete query object to perform a bulk delete operation.

Usage

From source file:org.mitre.oauth2.repository.impl.JpaOAuth2TokenRepository.java

@Override
@Transactional(value = "defaultTransactionManager")
public void clearDuplicateAccessTokens() {

    Query query = manager.createQuery(
            "select a.jwt, count(1) as c from OAuth2AccessTokenEntity a GROUP BY a.jwt HAVING c > 1");
    @SuppressWarnings("unchecked")
    List<Object[]> resultList = query.getResultList();
    List<JWT> values = new ArrayList<>();
    for (Object[] r : resultList) {
        logger.warn("Found duplicate access tokens: {}, {}", ((JWT) r[0]).serialize(), r[1]);
        values.add((JWT) r[0]);// w  w  w  . j  a  v  a 2s  .  c  o m
    }
    if (values.size() > 0) {
        CriteriaBuilder cb = manager.getCriteriaBuilder();
        CriteriaDelete<OAuth2AccessTokenEntity> criteriaDelete = cb
                .createCriteriaDelete(OAuth2AccessTokenEntity.class);
        Root<OAuth2AccessTokenEntity> root = criteriaDelete.from(OAuth2AccessTokenEntity.class);
        criteriaDelete.where(root.get("jwt").in(values));
        int result = manager.createQuery(criteriaDelete).executeUpdate();
        logger.warn("Deleted {} duplicate access tokens", result);
    }
}

From source file:org.mitre.oauth2.repository.impl.JpaOAuth2TokenRepository.java

@Override
@Transactional(value = "defaultTransactionManager")
public void clearDuplicateRefreshTokens() {
    Query query = manager.createQuery(
            "select a.jwt, count(1) as c from OAuth2RefreshTokenEntity a GROUP BY a.jwt HAVING c > 1");
    @SuppressWarnings("unchecked")
    List<Object[]> resultList = query.getResultList();
    List<JWT> values = new ArrayList<>();
    for (Object[] r : resultList) {
        logger.warn("Found duplicate refresh tokens: {}, {}", ((JWT) r[0]).serialize(), r[1]);
        values.add((JWT) r[0]);//from  w  w  w  . j  a v  a2 s  . c  om
    }
    if (values.size() > 0) {
        CriteriaBuilder cb = manager.getCriteriaBuilder();
        CriteriaDelete<OAuth2RefreshTokenEntity> criteriaDelete = cb
                .createCriteriaDelete(OAuth2RefreshTokenEntity.class);
        Root<OAuth2RefreshTokenEntity> root = criteriaDelete.from(OAuth2RefreshTokenEntity.class);
        criteriaDelete.where(root.get("jwt").in(values));
        int result = manager.createQuery(criteriaDelete).executeUpdate();
        logger.warn("Deleted {} duplicate refresh tokens", result);
    }

}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Erase all {@link FlowLogMessageType}s of the application scope older than
 * the given date.//from   www.ja va 2  s . c  o  m
 *
 * @param toDate
 *            the date.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public void eraseFlowLogMessage(final Date toDate) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaDelete<FlowLogMessageType> q = cb.createCriteriaDelete(FlowLogMessageType.class);
    final Root<FlowLogMessageType> c = q.from(FlowLogMessageType.class);
    q.where(cb.lessThan(c.<Date>get(FlowLogMessageType_.logTimeItem), toDate));
    try {
        this.em.createQuery(q).executeUpdate();
    } catch (final Exception e) {
        this.logger.error("eraseFlowLogMessage: {}", e.getMessage());
    }
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Erase all {@link SystemUserLogType}s of the application scope older than
 * the given date./* ww  w. j  a  v  a2s.c o  m*/
 *
 * @param toDate
 *            the date.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public void eraseSystemUserLog(final Date toDate) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaDelete<SystemUserLogType> q = cb.createCriteriaDelete(SystemUserLogType.class);
    final Root<SystemUserLogType> c = q.from(SystemUserLogType.class);
    q.where(cb.lessThan(c.<Date>get(SystemUserLogType_.logDateItem), toDate),
            cb.equal(c.<String>get(SystemUserLogType_.context), this.contextNameProvider.getContextName()));
    try {
        this.em.createQuery(q).executeUpdate();
    } catch (final Exception e) {
        this.logger.error("eraseSystemUserLog: {}", e.getMessage());
    }
}

From source file:com.qpark.eip.core.spring.statistics.dao.StatisticsLoggingDao.java

/**
 * Erase all {@link ApplicationUserLogType}s of the application scope older
 * than the given date.//from  w  w w . j av  a2 s . co  m
 *
 * @param toDate
 *            the date.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public void eraseApplicationUserLog(final Date toDate) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaDelete<ApplicationUserLogType> q = cb.createCriteriaDelete(ApplicationUserLogType.class);
    final Root<ApplicationUserLogType> c = q.from(ApplicationUserLogType.class);
    q.where(cb.lessThan(c.<Date>get(ApplicationUserLogType_.stopItem), toDate), cb
            .equal(c.<String>get(ApplicationUserLogType_.context), this.contextNameProvider.getContextName()));
    try {
        this.em.createQuery(q).executeUpdate();
    } catch (final Exception e) {
        this.logger.error("eraseApplicationUserLog: {}", e.getMessage());
    }
}

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

/**
 * {@inheritDoc}/*from   w  w w.  ja  v a 2s.c o  m*/
 */
@Override
public <T extends BaseEntity> int deleteByCriteria(DeleteCriteria<T> criteria) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaDelete<T> cd = cb.createCriteriaDelete(criteria.getEntity());
        Root<T> root = cd.from(criteria.getEntity());
        int rowsDeleted = em
                .createQuery(cd.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root))))
                .executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteByCriteria: 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:org.apache.ambari.server.upgrade.UpgradeCatalog210.java

/**
 * Delete STORM_REST_API component if HDP is upgraded past 2.2 and the
 * Component still exists./*w  ww. j  a va  2  s .c o m*/
 */
protected void removeStormRestApiServiceComponent() {
    AmbariManagementController ambariManagementController = injector
            .getInstance(AmbariManagementController.class);
    Clusters clusters = ambariManagementController.getClusters();

    if (clusters != null) {
        Map<String, Cluster> clusterMap = clusters.getClusters();
        for (final Cluster cluster : clusterMap.values()) {
            StackId stackId = cluster.getCurrentStackVersion();
            if (stackId != null && stackId.getStackName().equals("HDP")
                    && VersionUtils.compareVersions(stackId.getStackVersion(), "2.2") >= 0) {

                executeInTransaction(new Runnable() {
                    @Override
                    public void run() {
                        ServiceComponentDesiredStateDAO dao = injector
                                .getInstance(ServiceComponentDesiredStateDAO.class);
                        ServiceComponentDesiredStateEntityPK entityPK = new ServiceComponentDesiredStateEntityPK();
                        entityPK.setClusterId(cluster.getClusterId());
                        entityPK.setServiceName("STORM");
                        entityPK.setComponentName("STORM_REST_API");
                        ServiceComponentDesiredStateEntity entity = dao.findByPK(entityPK);
                        if (entity != null) {
                            EntityManager em = getEntityManagerProvider().get();
                            CriteriaBuilder cb = em.getCriteriaBuilder();

                            try {
                                LOG.info("Deleting STORM_REST_API service component.");
                                CriteriaDelete<HostComponentStateEntity> hcsDelete = cb
                                        .createCriteriaDelete(HostComponentStateEntity.class);
                                CriteriaDelete<HostComponentDesiredStateEntity> hcdDelete = cb
                                        .createCriteriaDelete(HostComponentDesiredStateEntity.class);
                                CriteriaDelete<ServiceComponentDesiredStateEntity> scdDelete = cb
                                        .createCriteriaDelete(ServiceComponentDesiredStateEntity.class);

                                Root<HostComponentStateEntity> hcsRoot = hcsDelete
                                        .from(HostComponentStateEntity.class);
                                Root<HostComponentDesiredStateEntity> hcdRoot = hcdDelete
                                        .from(HostComponentDesiredStateEntity.class);
                                Root<ServiceComponentDesiredStateEntity> scdRoot = scdDelete
                                        .from(ServiceComponentDesiredStateEntity.class);

                                hcsDelete.where(cb.equal(hcsRoot.get("componentName"), "STORM_REST_API"));
                                hcdDelete.where(cb.equal(hcdRoot.get("componentName"), "STORM_REST_API"));
                                scdDelete.where(cb.equal(scdRoot.get("componentName"), "STORM_REST_API"));

                                em.createQuery(hcsDelete).executeUpdate();
                                em.createQuery(hcdDelete).executeUpdate();
                                em.createQuery(scdDelete).executeUpdate();
                            } catch (Exception e) {
                                LOG.warn("Error deleting STORM_REST_API service component. "
                                        + "This could result in issue with ambari server start. "
                                        + "Please make sure the STORM_REST_API component is deleted "
                                        + "from the database by running following commands:\n"
                                        + "delete from hostcomponentdesiredstate where component_name='STORM_REST_API';\n"
                                        + "delete from hostcomponentstate where component_name='STORM_REST_API';\n"
                                        + "delete from servicecomponentdesiredstate where component_name='STORM_REST_API';\n",
                                        e);
                            }
                        }
                    }
                });
            }
        }
    }
}

From source file:org.fao.geonet.repository.HarvesterSettingRepositoryOverridesImpl.java

/**
 * Overrides the implementation in {@link org.springframework.data.jpa.repository.support.SimpleJpaRepository}.
 * This implementation deleted the thentity and all children.
 *
 * @param settingId the id of the entity to delete
 *///from  w  w w.  j a va  2s.co m
@Transactional
public void delete(final int settingId) {
    final List<Integer> toRemove = Lists.newArrayList(settingId);
    int i = 0;
    while (i < toRemove.size()) {
        final int nextParentId = toRemove.get(i);
        toRemove.addAll(findAllChildIds(nextParentId));
        i++;
    }

    final CriteriaBuilder cb = _entityManager.getCriteriaBuilder();
    final CriteriaDelete<HarvesterSetting> delete = cb.createCriteriaDelete(HarvesterSetting.class);
    final Root<HarvesterSetting> root = delete.from(HarvesterSetting.class);

    delete.where(root.get(HarvesterSetting_.id).in(toRemove));

    _entityManager.createQuery(delete).executeUpdate();

    _entityManager.flush();
    _entityManager.clear();
}