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.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}//www  .  j  a  v  a 2  s .com
 */
@Override
public int executeByNamedQuery(final String name, final Object... params) {
    String queryString = getJpqlQuery(name);
    Query queryObject = getEntityManager().createQuery(queryString);
    if (params != null) {
        int i = 0;
        for (Object obj : params) {
            queryObject.setParameter(i, obj);
        }
    }
    return queryObject.executeUpdate();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerJpaController.java

public void deleteAllSubscribedResources() {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from   ww  w .j  av  a2 s.c o  m*/

    Query q = entityManager.createQuery("DELETE FROM SubscribedResource ");
    q.executeUpdate();
    entityManager.flush();

    entityTransaction.commit();

}

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

public int updatePrivateMessagesToTrash(List<Long> privateMessageIds, Boolean isTrash,
        Long privateMessageFolderId) {
    try {/* w w w  .  j a va2s.co m*/
        Query query = em.createNamedQuery("updatePrivateMessagesToTrash");
        query.setParameter("isTrash", isTrash);
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        query.setParameter("privateMessageIds", privateMessageIds);
        int updatedEntities = query.executeUpdate();

        //Refresh the Entities in the Cache as Hibernate will not do it!
        //FIXME weird code
        for (Long privateMessageId : privateMessageIds) {
            TypedQuery<PrivateMessage> querySel = em.createNamedQuery("getPrivateMessagesById",
                    PrivateMessage.class);
            querySel.setParameter("privateMessageId", privateMessageId);
            try {
                querySel.getSingleResult();
            } catch (NoResultException ex) {
            }
        }

        return updatedEntities;
    } catch (Exception e) {
        log.error("[updatePrivateMessagesToTrash]", e);
    }
    return -1;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAGroupDAO.java

@Transactional
@Override/*w  w w  . j  a va  2 s. co  m*/
public Pair<Set<String>, Set<String>> refreshDynMemberships(final User user) {
    Set<String> before = new HashSet<>();
    Set<String> after = new HashSet<>();
    findWithUDynMemberships().stream().map(memb -> {
        Query delete = entityManager()
                .createNativeQuery("DELETE FROM " + UDYNMEMB_TABLE + " WHERE group_id=? AND any_id=?");
        delete.setParameter(1, memb.getGroup().getKey());
        delete.setParameter(2, user.getKey());

        if (delete.executeUpdate() > 0) {
            before.add(memb.getGroup().getKey());
        }

        if (jpaAnySearchDAO().matches(user,
                buildDynMembershipCond(memb.getFIQLCond(), memb.getGroup().getRealm()))) {

            Query insert = entityManager().createNativeQuery("INSERT INTO " + UDYNMEMB_TABLE + " VALUES(?, ?)");
            insert.setParameter(1, user.getKey());
            insert.setParameter(2, memb.getGroup().getKey());
            insert.executeUpdate();

            after.add(memb.getGroup().getKey());
        }
        return memb;
    }).forEachOrdered(memb -> publisher
            .publishEvent(new AnyCreatedUpdatedEvent<>(this, memb.getGroup(), AuthContextUtils.getDomain())));

    return Pair.of(before, after);
}

From source file:org.opentides.dao.impl.BaseEntityDaoJpaImpl.java

/**
 * {@inheritDoc}/*from   w  ww.j  av  a2  s  .  c  om*/
 */
@Override
public int executeByNamedQuery(final String name, final Map<String, Object> params) {
    String queryString = getJpqlQuery(name);
    Query queryObject = getEntityManager().createQuery(queryString);
    if (params != null) {
        for (Map.Entry<String, Object> entry : params.entrySet())
            queryObject.setParameter(entry.getKey(), entry.getValue());
    }
    return queryObject.executeUpdate();
}

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

@SuppressWarnings("unused")
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
//@TransactionTimeout( 60 * 60 )
private int _calculateAutoBaselinesINSERT_HQL(long startTime, long endTime, long computeTime) throws Exception {
    Query query = entityManager.createNamedQuery(MeasurementBaseline.QUERY_CALC_FIRST_AUTOBASELINE);

    //query.setParameter("computeTime", computeTime);
    query.setParameter("startTime", startTime);
    query.setParameter("endTime", endTime);

    int rowsModified = query.executeUpdate();

    return rowsModified;
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAGroupDAO.java

@Transactional
@Override//ww  w .  j  a va  2 s  . c  om
public Pair<Set<String>, Set<String>> refreshDynMemberships(final AnyObject anyObject) {
    Set<String> before = new HashSet<>();
    Set<String> after = new HashSet<>();
    findWithADynMemberships(anyObject.getType()).stream().map(memb -> {
        Query delete = entityManager()
                .createNativeQuery("DELETE FROM " + ADYNMEMB_TABLE + " WHERE group_id=? AND any_id=?");
        delete.setParameter(1, memb.getGroup().getKey());
        delete.setParameter(2, anyObject.getKey());

        if (delete.executeUpdate() > 0) {
            before.add(memb.getGroup().getKey());
        }

        if (jpaAnySearchDAO().matches(anyObject,
                buildDynMembershipCond(memb.getFIQLCond(), memb.getGroup().getRealm()))) {

            Query insert = entityManager()
                    .createNativeQuery("INSERT INTO " + ADYNMEMB_TABLE + " VALUES(?, ?, ?)");
            insert.setParameter(1, anyObject.getType().getKey());
            insert.setParameter(2, anyObject.getKey());
            insert.setParameter(3, memb.getGroup().getKey());
            insert.executeUpdate();

            after.add(memb.getGroup().getKey());
        }
        return memb;
    }).forEachOrdered(memb -> publisher
            .publishEvent(new AnyCreatedUpdatedEvent<>(this, memb.getGroup(), AuthContextUtils.getDomain())));

    return Pair.of(before, after);
}

From source file:org.apache.syncope.core.persistence.jpa.dao.JPAGroupDAO.java

@Override
public Group save(final Group group) {
    Group merged = super.save(group);
    publisher.publishEvent(new AnyCreatedUpdatedEvent<>(this, merged, AuthContextUtils.getDomain()));

    // refresh dynamic memberships
    clearUDynMembers(merged);/*from w w  w .  java  2 s . c  o  m*/
    if (merged.getUDynMembership() != null) {
        SearchCond cond = buildDynMembershipCond(merged.getUDynMembership().getFIQLCond(), merged.getRealm());
        int count = searchDAO().count(Collections.<String>singleton(merged.getRealm().getFullPath()), cond,
                AnyTypeKind.USER);
        for (int page = 1; page <= (count / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
            List<User> matching = searchDAO().search(
                    Collections.<String>singleton(merged.getRealm().getFullPath()), cond, page,
                    AnyDAO.DEFAULT_PAGE_SIZE, Collections.<OrderByClause>emptyList(), AnyTypeKind.USER);

            matching.forEach(user -> {
                Query insert = entityManager()
                        .createNativeQuery("INSERT INTO " + UDYNMEMB_TABLE + " VALUES(?, ?)");
                insert.setParameter(1, user.getKey());
                insert.setParameter(2, merged.getKey());
                insert.executeUpdate();

                publisher.publishEvent(new AnyCreatedUpdatedEvent<>(this, user, AuthContextUtils.getDomain()));
            });
        }
    }
    clearADynMembers(merged);
    merged.getADynMemberships().stream().forEach(memb -> {
        SearchCond cond = buildDynMembershipCond(memb.getFIQLCond(), merged.getRealm());
        int count = searchDAO().count(Collections.<String>singleton(merged.getRealm().getFullPath()), cond,
                AnyTypeKind.ANY_OBJECT);
        for (int page = 1; page <= (count / AnyDAO.DEFAULT_PAGE_SIZE) + 1; page++) {
            List<AnyObject> matching = searchDAO().search(
                    Collections.<String>singleton(merged.getRealm().getFullPath()), cond, page,
                    AnyDAO.DEFAULT_PAGE_SIZE, Collections.<OrderByClause>emptyList(), AnyTypeKind.ANY_OBJECT);

            matching.forEach(anyObject -> {
                Query insert = entityManager()
                        .createNativeQuery("INSERT INTO " + ADYNMEMB_TABLE + " VALUES(?, ?, ?)");
                insert.setParameter(1, anyObject.getType().getKey());
                insert.setParameter(2, anyObject.getKey());
                insert.setParameter(3, merged.getKey());
                insert.executeUpdate();

                publisher.publishEvent(
                        new AnyCreatedUpdatedEvent<>(this, anyObject, AuthContextUtils.getDomain()));
            });
        }
    });

    dynRealmDAO().refreshDynMemberships(merged);

    return merged;
}

From source file:org.openmeetings.app.data.user.dao.PrivateMessagesDaoImpl.java

public int updatePrivateMessagesToTrash(List<Long> privateMessageIds, Boolean isTrash,
        Long privateMessageFolderId) {
    try {//from   www. ja v  a 2  s  .  c  o  m

        String hql = "UPDATE PrivateMessages c "
                + "SET c.isTrash = :isTrash,c.privateMessageFolderId = :privateMessageFolderId "
                + "where c.privateMessageId IN (:privateMessageIds) ";

        Query query = em.createQuery(hql);
        query.setParameter("isTrash", isTrash);
        query.setParameter("privateMessageFolderId", privateMessageFolderId);
        query.setParameter("privateMessageIds", privateMessageIds);
        int updatedEntities = query.executeUpdate();

        //Refresh the Entities in the Cache as Hibernate will not do it!
        //FIXME weird code
        for (Long privateMessageId : privateMessageIds) {
            String hqlSel = "select c from PrivateMessages c "
                    + "where c.privateMessageId = :privateMessageId ";

            TypedQuery<PrivateMessages> querySel = em.createQuery(hqlSel, PrivateMessages.class);
            querySel.setParameter("privateMessageId", privateMessageId);

            try {
                querySel.getSingleResult();
            } catch (NoResultException ex) {
            }
        }

        return updatedEntities;
    } catch (Exception e) {
        log.error("[updatePrivateMessagesToTrash]", e);
    }
    return -1;
}

From source file:org.apache.falcon.state.store.jdbc.JDBCStateStore.java

@Override
public void updateEntity(EntityState entityState) throws StateStoreException {
    EntityID entityID = new EntityID(entityState.getEntity());
    if (!entityExists(entityID)) {
        throw new StateStoreException("Entity with key, " + entityID + " doesn't exists.");
    }//from  w ww. j a v  a 2s.com
    EntityManager entityManager = getEntityManager();
    beginTransaction(entityManager);
    Query q = entityManager.createNamedQuery(PersistenceConstants.UPDATE_ENTITY);
    q.setParameter("id", entityID.getKey());
    if (entityState.getCurrentState() != null) {
        q.setParameter("state", entityState.getCurrentState().toString());
    }
    q.setParameter("type", entityState.getEntity().getEntityType().toString());
    q.setParameter("name", entityState.getEntity().getName());
    q.executeUpdate();
    commitAndCloseTransaction(entityManager);
}