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.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}//from   w w w .  j  av  a  2s .co m
 */
@Override
public Integer restoreMyHistory(User user, Category category) throws PersistenceException {
    String updateString = "UPDATE UserHistory set logicaldelete=true WHERE user=:user and category=:category and logicalDelete=true";

    Query query = getEntityManager().createQuery(updateString);

    query.setParameter("user", user);
    query.setParameter("category", category);

    return query.executeUpdate();
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}//from ww w.j  av  a 2s.c o m
 */
@Override
public Integer restoreUserHistory(User user, Category category) throws PersistenceException {
    String updateString = "UPDATE UserHistory set logicaldelete=true WHERE user=:user and category=:category and logicalDelete=true";

    Query query = getEntityManager().createQuery(updateString);

    query.setParameter("user", user);
    query.setParameter("category", category);

    return query.executeUpdate();
}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

public int updateSchedulesForContext(Subject subject, EntityContext context, int[] measurementDefinitionIds,
        long collectionInterval) {
    collectionInterval = verifyMinimumCollectionInterval(collectionInterval);

    String measurementScheduleSubQuery = getMeasurementScheduleSubQueryForContext(subject, context,
            measurementDefinitionIds);//  ww  w  .ja v a 2 s .c  o  m

    String updateQuery = "" //
            + "UPDATE MeasurementSchedule " //
            + "   SET interval = :interval, " //
            + "       enabled = true " //
            + " WHERE id IN ( " + measurementScheduleSubQuery + " ) ";

    Query query = entityManager.createQuery(updateQuery);
    query.setParameter("interval", collectionInterval);
    int affectedRows = query.executeUpdate();

    scheduleJobToPushScheduleUpdatesToAgents(context, measurementScheduleSubQuery);

    return affectedRows;
}

From source file:org.medici.bia.dao.userhistory.UserHistoryDAOJpaImpl.java

/**
 * {@inheritDoc}//from w w  w .  ja  v  a2s . co  m
 */
@Override
public Integer renameAccount(String originalAccount, String newAccount) throws PersistenceException {
    String jpql = "UPDATE UserHistory SET user.account=:newAccount WHERE user.account=:originalAccount";
    Query query = getEntityManager().createQuery(jpql);
    query.setParameter("newAccount", newAccount);
    query.setParameter("originalAccount", originalAccount);

    return query.executeUpdate();
}

From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java

@Override
public void updateSomeAttributes(final ENTITY entity) {
    if (entity.getId() == null) {
        LOG.debug(entity.getClass().getSimpleName() + " id not found");
        return;/*from   w  w w  .j  a  va2s .  co m*/
    }
    final StringBuilder sql = new StringBuilder(getUpdateSomeAttributtesSQL(entity));
    try {
        final VulpeHashMap<String, Object> map = getUpdateSomeAttributesMap(entity);
        final Field idField = VulpeReflectUtil.getField(entity.getClass(), "id");
        final Column column = idField.getAnnotation(Column.class);
        sql.append(column != null ? column.name() : "id").append(" = ").append(entity.getId());
        final Query query = entityManager.createNativeQuery(sql.toString());
        for (final String key : map.keySet()) {
            final Object value = map.get(key);
            if (value instanceof Enum) {
                query.setParameter(key, value.toString());
            } else if (value instanceof VulpeEntity) {
                query.setParameter(key, ((VulpeEntity<ID>) value).getId());
            } else {
                query.setParameter(key, value);
            }
        }
        query.executeUpdate();
        entityManager.flush();
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
}

From source file:org.vulpe.model.dao.impl.jpa.AbstractVulpeBaseDAOJPA.java

@Override
public void updateSomeAttributes(final ENTITY entity, final List<ID> ids) {
    if (VulpeValidationUtil.isEmpty(ids)) {
        LOG.debug(entity.getClass().getSimpleName() + " id list not found");
        return;//from  w w w  . j  ava  2  s. c  o m
    }
    final StringBuilder sql = new StringBuilder(getUpdateSomeAttributtesSQL(entity));
    try {
        final VulpeHashMap<String, Object> map = getUpdateSomeAttributesMap(entity);
        StringBuilder sqlIds = new StringBuilder();
        for (final ID id : ids) {
            if (sqlIds.length() > 0) {
                sqlIds.append(",");
            }
            sqlIds.append(((Long) id).intValue());
        }
        final Field idField = VulpeReflectUtil.getField(entity.getClass(), "id");
        final Column column = idField.getAnnotation(Column.class);
        sql.append(column != null ? column.name() : "id").append(" in (").append(sqlIds).append(")");
        final Query query = entityManager.createNativeQuery(sql.toString());
        for (final String key : map.keySet()) {
            final Object value = map.get(key);
            if (value instanceof Enum) {
                query.setParameter(key, value.toString());
            } else if (value instanceof VulpeEntity) {
                query.setParameter(key, ((VulpeEntity<ID>) value).getId());
            } else {
                query.setParameter(key, value);
            }
        }
        query.executeUpdate();
        entityManager.flush();
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
}

From source file:com.lhfs.fsn.dao.testReport.impl.TestReportDaoImpl.java

/**
 * ??//  ww  w . ja v  a2s. c om
 * publishFlag 5    6   1???
 * @author ZhangHui 2015/4/9
 */
@Override
public void updatePublishFlag(char publishFlag, long reportId, String msg, String checkOrgName)
        throws DaoException {
    try {
        String userName = AccessUtils.getUserName() != null ? AccessUtils.getUserName().toString() : null;
        String sql = "";
        if (publishFlag == '5') {
            if (msg == null) {
                msg = "";
            }
            sql = "UPDATE test_result SET publish_flag = ?1,back_time = now(),back_result= ?2,check_org_name=?4 WHERE id = ?3";
        } else if (publishFlag == '6') {
            msg = "";
            sql = "UPDATE test_result SET publish_flag = ?1,receiveDate = now(),back_result= ?2,check_org_name=?4 WHERE id = ?3";
        } else {//???portal
            msg = "";
            sql = "UPDATE test_result SET publish_flag = ?1,receiveDate = now(),pub_user_name=?5,publishDate = now(),back_result= ?2,check_org_name=?4 WHERE id = ?3";
        }
        Query query = entityManager.createNativeQuery(sql);
        query.setParameter(1, publishFlag);
        query.setParameter(2, msg);
        query.setParameter(3, reportId);
        query.setParameter(4, checkOrgName);
        if (publishFlag == '1') {
            query.setParameter(5, userName);
        }
        query.executeUpdate();
    } catch (Exception e) {
        throw new DaoException("FromToBussinessDAOImpl.updatePublishFlag() ?", e);
    }
}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

/**
 * The mtime on the Resources will tell the Agent it needs to pull down the
 * latest schedules next time it performs an Agent-Server sync.
 *
 * @param context the entity context//from w w  w  .  ja  v a2  s . com
 * @param agentId the agent id
 */
private void markResources(EntityContext context, int agentId) {
    ResourceCriteria criteria = new ResourceCriteria();
    if (context.type == EntityContext.Type.Resource) {
        criteria.addFilterId(context.resourceId);
    } else if (context.type == EntityContext.Type.ResourceGroup) {
        criteria.addFilterImplicitGroupIds(context.groupId);
    } else if (context.type == EntityContext.Type.AutoGroup) {
        criteria.addFilterParentResourceId(context.parentResourceId);
        criteria.addFilterResourceTypeId(context.resourceTypeId);
    }
    criteria.addFilterAgentId(agentId);

    try {
        CriteriaQueryGenerator generator = new CriteriaQueryGenerator(criteria);
        ;
        generator.alterProjection("resource.id");
        String resourceSubQuery = generator.getParameterReplacedQuery(false);

        String markResourceQueryString = "" //
                + "UPDATE Resource res " //
                + "   SET res.mtime = :now " //
                + " WHERE res.id IN ( " + resourceSubQuery + " ) ";
        if (log.isDebugEnabled()) {
            log.debug("markResourceQueryString: " + markResourceQueryString);
        }

        Query markResourceQuery = entityManager.createQuery(markResourceQueryString);
        markResourceQuery.setParameter("now", System.currentTimeMillis());
        int affectedRows = markResourceQuery.executeUpdate();
        if (log.isDebugEnabled()) {
            log.debug("Marked " + affectedRows + " for future measurement scheudle update");
        }
    } catch (Throwable t) {
        log.error("Could not notify agents of updates", t);
    }
}

From source file:org.rhq.enterprise.server.measurement.MeasurementScheduleManagerBean.java

@SuppressWarnings("unchecked")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public void errorCorrectSchedules() {
    /* /*  w  ww .  j  a v  a  2s  .c o  m*/
     * update mtime of resources whose schedules are < 30s, this will indicate to the 
     * agent that it needs to sync / merge schedules for the resources updated here
     */
    try {
        long now = System.currentTimeMillis();
        String updateResourcesQueryString = "" //
                + " UPDATE Resource " //
                + "    SET mtime = :currentTime " //
                + "  WHERE id IN ( SELECT ms.resource.id " //
                + "                  FROM MeasurementSchedule ms " // 
                + "                 WHERE ms.interval < 30000 ) ";
        Query updateResourcesQuery = entityManager.createQuery(updateResourcesQueryString);
        updateResourcesQuery.setParameter("currentTime", now);
        int resourcesUpdatedCount = updateResourcesQuery.executeUpdate();

        // update schedules to 30s whose schedules are < 30s
        String updateSchedulesQueryString = "" //
                + " UPDATE MeasurementSchedule " //
                + "    SET interval = 30000 " //
                + "  WHERE interval < 30000 ";
        Query updateSchedulesQuery = entityManager.createQuery(updateSchedulesQueryString);
        int schedulesUpdatedCount = updateSchedulesQuery.executeUpdate();

        if (resourcesUpdatedCount > 0) {
            // now try to tell the agents that certain resources have changed
            String findResourcesQueryString = "" //
                    + " SELECT res.id " //
                    + "   FROM Resource res " //
                    + "  WHERE res.mtime = :currentTime ";
            Query findResourcesQuery = entityManager.createQuery(findResourcesQueryString);
            findResourcesQuery.setParameter("currentTime", now);
            List<Integer> updatedResourceIds = findResourcesQuery.getResultList();
            updateMeasurementSchedulesForResources(ArrayUtils.unwrapCollection(updatedResourceIds));

            log.error("MeasurementSchedule data was corrupt: automatically updated " + resourcesUpdatedCount
                    + " resources and " + schedulesUpdatedCount
                    + " to correct the issue; agents were notified");
        } else {
            if (log.isDebugEnabled()) {
                log.debug("MeasurementSchedule data was checked for corruption, but all data was consistent");
            }
        }
    } catch (Throwable t) {
        log.error("There was a problem correcting errors for MeasurementSchedules", t);
    }
}

From source file:com.gettec.fsnip.fsn.dao.member.impl.MemberDAOImpl.java

@Override
public boolean setBarcodeToQRcode(String barcode, Long memberID, String QRStart, String QREnd) {
    //???0?/*from  ww  w  . j  a  v a2  s .co m*/
    String isExist = "SELECT pb.start_num,pb.end_num  FROM member_barcode_to_qrcode pb WHERE ?1  BETWEEN start_num and end_num OR ?2 BETWEEN start_num AND end_num or ?1<=start_num AND ?2>=end_num";
    Query isExistQuery = entityManager.createNativeQuery(isExist);
    isExistQuery.setParameter(1, QRStart);
    isExistQuery.setParameter(2, QREnd);
    int existSize = isExistQuery.getResultList().size();
    //0??
    if (existSize == 0) {
        String insertSql = "INSERT INTO member_barcode_to_qrcode (member_barcode,member_id,start_num,end_num  )VALUES (?1,?2,?3,?4) ";
        Query insertQuery = entityManager.createNativeQuery(insertSql);
        insertQuery.setParameter(1, barcode);
        insertQuery.setParameter(2, memberID);
        insertQuery.setParameter(3, QRStart);
        insertQuery.setParameter(4, QREnd);
        int success = insertQuery.executeUpdate();
        System.out.print("----sql----" + success);
        if (success == 1) {
            return true;
        } else {
            return false;
        }

    }
    return false;

}