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.sitemapindex.SitemapIndexDAOJpaImpl.java

/**
 * {@inheritDoc}/*  ww  w  .  java  2  s.com*/
 */
@Override
public Integer deleteSitemapIndex() throws PersistenceException {
    String sql = "TRUNCATE TABLE tblSitemapIndex";

    Query query = getEntityManager().createNativeQuery(sql);
    Integer truncateResult = query.executeUpdate();

    return truncateResult;
}

From source file:org.orcid.persistence.dao.impl.OtherNameDaoImpl.java

/**
 * Delete other name from database//from  ww w . j  av a  2 s.  c  o m
 * @param otherName
 * @return 
 *          true if the other name was successfully deleted, false otherwise
 * */
@Override
@Transactional
public boolean deleteOtherName(OtherNameEntity otherName) {
    Assert.notNull(otherName);
    Query query = entityManager.createQuery("DELETE FROM OtherNameEntity WHERE id=:id");
    query.setParameter("id", otherName.getId());
    return query.executeUpdate() > 0 ? true : false;
}

From source file:de.berlios.jhelpdesk.dao.jpa.TicketFilterDAOJpa.java

@Transactional(readOnly = false)
public void delete(final Long filterId) {
    this.jpaTemplate.execute(new JpaCallback<TicketFilter>() {
        public TicketFilter doInJpa(EntityManager em) throws PersistenceException {
            Query q = em.createQuery("DELETE FROM TicketFilter f WHERE f.ticketFilterId = ?1");
            q.setParameter(1, filterId);
            q.executeUpdate();
            return null;
        }//from w  ww . ja  va 2  s.  com
    });
}

From source file:bankconsoleapp.repositories.SavingDao.java

@Transactional
public void deposit(String acnum, int amount) {

    int newBalance = 0;

    Query q1 = em.createQuery("From SavingAccount SA WHERE SA.accNum='" + acnum + "'");
    List<SavingAccount> SA = q1.getResultList();
    for (SavingAccount sav : SA) {
        newBalance = sav.getBalance() + amount;
    }// ww w  . jav  a  2s.c  o  m

    Query q = em.createQuery("update SavingAccount set balance=:bal where accNum=:an");
    q.setParameter("an", acnum);
    q.setParameter("bal", newBalance);
    q.executeUpdate();

    em.flush();

}

From source file:bankconsoleapp.repositories.SavingDao.java

@Transactional
public void withdraw(String acnum, int amount) {

    int newBalance = 0;

    Query q1 = em.createQuery("From SavingAccount SA WHERE SA.accNum='" + acnum + "'");
    List<SavingAccount> SA = q1.getResultList();
    for (SavingAccount sav : SA) {
        newBalance = sav.getBalance() - amount;
    }//from   www .ja v  a  2  s .com

    Query q = em.createQuery("update SavingAccount set balance=:bal where accNum=:an");
    q.setParameter("an", acnum);
    q.setParameter("bal", newBalance);
    q.executeUpdate();

    em.flush();

}

From source file:modelo.DaoTiposActividadesImpl.java

@Override
public void eliminarActividad(int idtipoActividad) {
    /* EntityManager em=this.obtenerEntityManager();
     Actividad act=em.find(Actividad.class,idactividades);
     EntityTransaction tx=em.getTransaction();
     tx.begin();// w  w w.j  a v a  2  s  .  c  o m
     em.remove(act);
     tx.commit();
     em.close();*/

    String jpql = "delete from Actividad act where act.idactividades=?1";

    Query q = em.createQuery(jpql);
    q.setParameter(1, idtipoActividad);
    EntityTransaction tx = em.getTransaction();
    tx.begin();
    q.executeUpdate();
    tx.commit();
    em.close();

}

From source file:me.doshou.admin.monitor.web.controller.SQLExecutorController.java

@PageableDefaults(pageNumber = 0, value = 10)
@RequestMapping(value = "/sql", method = RequestMethod.POST)
public String executeQL(final @RequestParam("sql") String sql, final Model model, final Pageable pageable) {

    model.addAttribute("sessionFactory", HibernateUtils.getSessionFactory(em));

    String lowerCaseSQL = sql.trim().toLowerCase();
    final boolean isDML = lowerCaseSQL.startsWith("insert") || lowerCaseSQL.startsWith("update")
            || lowerCaseSQL.startsWith("delete");
    final boolean isDQL = lowerCaseSQL.startsWith("select");

    if (!isDML && !isDQL) {
        model.addAttribute(Constants.ERROR,
                "SQL????insert?update?delete?select");
        return showSQLForm();
    }//from  w ww . j av  a  2s.c  o m
    try {
        new TransactionTemplate(transactionManager).execute(new TransactionCallback<Void>() {
            @Override
            public Void doInTransaction(TransactionStatus status) {

                if (isDML) {
                    Query query = em.createNativeQuery(sql);
                    int updateCount = query.executeUpdate();
                    model.addAttribute("updateCount", updateCount);
                } else {
                    String findSQL = sql;
                    String countSQL = "select count(*) count from (" + findSQL + ") o";
                    Query countQuery = em.createNativeQuery(countSQL);
                    Query findQuery = em.createNativeQuery(findSQL);
                    findQuery.setFirstResult(pageable.getOffset());
                    findQuery.setMaxResults(pageable.getPageSize());

                    Page page = new PageImpl(findQuery.getResultList(), pageable,
                            ((BigInteger) countQuery.getSingleResult()).longValue());

                    model.addAttribute("resultPage", page);

                    em.unwrap(Session.class).doWork(new Work() {
                        @Override
                        public void execute(final Connection connection) throws SQLException {
                            PreparedStatement psst = connection.prepareStatement(sql);
                            ResultSetMetaData metaData = psst.getMetaData();

                            List<String> columnNames = Lists.newArrayList();
                            for (int i = 1, l = metaData.getColumnCount(); i <= l; i++) {
                                columnNames.add(metaData.getColumnLabel(i));
                            }
                            psst.close();
                            model.addAttribute("columnNames", columnNames);
                        }
                    });
                }

                return null;
            }
        });
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        model.addAttribute(Constants.ERROR, sw.toString());
    }

    return showSQLForm();
}

From source file:com.expressui.sample.dao.UserReferenceCleanupAdvice.java

@Before("(bean(genericDao) || bean(userDao)) && execution(* *.remove(Object)) && args(user)")
@Transactional//from www  . j  a v  a 2  s  .  c  o  m
public void remove(User user) {
    Query query = entityManager
            .createQuery("UPDATE Account a SET a.assignedTo = null WHERE a.assignedTo = :user");
    query.setParameter("user", user);
    query.executeUpdate();

    query = entityManager.createQuery("UPDATE Contact c SET c.assignedTo = null WHERE c.assignedTo = :user");
    query.setParameter("user", user);
    query.executeUpdate();

    query = entityManager
            .createQuery("UPDATE Opportunity o SET o.assignedTo = null WHERE o.assignedTo = :user");
    query.setParameter("user", user);
    query.executeUpdate();
}

From source file:com.github.iexel.fontus.services.ProductsService.java

@Override
@Transactional(rollbackFor = Throwable.class)
public void deleteProduct(int productId, int productVersion) throws ServiceException {

    Query query = entityManager.createNamedQuery("Product.delete");
    query.setParameter("id", productId);
    query.setParameter("version", productVersion);
    int numberOfRecords = query.executeUpdate();

    if (numberOfRecords == 0) {
        throw new ServiceException(ServiceException.ErrorCode.EXCEPTION_MODIFIED_BY_ANOTHER_USER);
    }/*  w w w .  j a va  2  s.c o m*/
}

From source file:com.doculibre.constellio.wicket.pages.SQLPage.java

public SQLPage() {
    super();//w w w.  jav  a 2 s  .c  o m
    ConstellioSession session = ConstellioSession.get();
    ConstellioUser user = session.getUser();
    boolean redirect;
    if (user == null) {
        redirect = true;
    } else if (user.isAdmin()) {
        redirect = false;
    } else {
        redirect = true;
        RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
        for (RecordCollection collection : collectionServices.list()) {
            if (user.hasCollaborationPermission(collection) || user.hasAdminPermission(collection)) {
                redirect = false;
                break;
            }
        }
    }
    if (redirect) {
        setResponsePage(getApplication().getHomePage());
    } else {
        form = new Form("form");
        feedbackPanel = new FeedbackPanel("feedback");
        textArea = new TextArea("query", queryModel);
        submitButton = new Button("submitButton") {
            @Override
            public void onSubmit() {
                String sql = (String) queryModel.getObject();
                if (StringUtils.isNotBlank(sql)) {
                    EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
                    if (!entityManager.getTransaction().isActive()) {
                        entityManager.getTransaction().begin();
                    }
                    Query sqlQuery = entityManager.createNativeQuery(sql);
                    try {
                        int rowCount = sqlQuery.executeUpdate();
                        entityManager.getTransaction().commit();
                        info(rowCount + " " + getLocalizer().getString("affectedRows", this));
                    } catch (Exception e) {
                        String stack = ExceptionUtils.getFullStackTrace(e);
                        error(stack);
                    }
                }
            }
        };

        add(form);
        form.add(feedbackPanel);
        form.add(textArea);
        form.add(submitButton);
    }
}