Example usage for javax.persistence EntityTransaction commit

List of usage examples for javax.persistence EntityTransaction commit

Introduction

In this page you can find the example usage for javax.persistence EntityTransaction commit.

Prototype

public void commit();

Source Link

Document

Commit the current resource transaction, writing any unflushed changes to the database.

Usage

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

protected void commitTransaction() throws ServiceException {
    try {//  w  ww.j a  v a 2s .  c  o  m
        EntityTransaction transaction = currentEntityManager().getTransaction();
        if (transaction.isActive()) {
            transaction.commit();
        }
    } catch (Exception e) {
        rollbackTransaction();
        throw new ServiceException("Can't commit transaction", e);
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskService.java

/**
 * Uploads input files. The method store input files for the specified task.
 * Input files are provided as a <i>multipart form data</i> using the field
 * file. This can contains multiple file using the html input attribute
 * <i>multiple="multiple"</i> which allows to associate multiple files with
 * a single field./*from  w w w  .j ava  2s . c o m*/
 *
 * @param id The task id retrieved from the url path
 * @param lstFiles List of file in the POST body
 */
@Path("/input")
@POST
@Consumes({ MediaType.MULTIPART_FORM_DATA })
public final void setInputFile(@PathParam("id") final String id,
        @FormDataParam("file") final List<FormDataBodyPart> lstFiles) {
    if (lstFiles == null || lstFiles.isEmpty()) {
        throw new BadRequestException("Input not accessible!");
    }
    EntityManager em = getEntityManager();
    Task task = em.find(Task.class, id);
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    if (task == null) {
        throw new NotFoundException("Task " + id + " does not exist");
    }
    for (FormDataBodyPart fdbp : lstFiles) {
        final String fName = fdbp.getFormDataContentDisposition().getFileName();
        try {
            Storage store = getStorage();
            store.storeFile(Storage.RESOURCE.TASKS, id, fdbp.getValueAs(InputStream.class), fName);
            EntityTransaction et = em.getTransaction();
            try {
                et.begin();
                task.updateInputFileStatus(fName, TaskFile.FILESTATUS.READY);
                et.commit();
            } catch (RuntimeException re) {
                if (et != null && et.isActive()) {
                    et.rollback();
                }
                log.error(re);
                log.error("Impossible to update the task");
                throw new InternalServerErrorException("Errore to update " + "the task");
            } finally {
                em.close();
            }
        } catch (IOException ex) {
            log.error(ex);
            throw new InternalServerErrorException("Errore to store input " + "files");
        }
    }
    em.close();
}

From source file:test.unit.be.fedict.hsm.entity.PersistenceTest.java

@Test
public void testApplicationKey() throws Exception {
    ApplicationEntity applicationEntity = new ApplicationEntity("app");

    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();/*www  . j  av  a  2  s .  c o  m*/
    this.entityManager.persist(applicationEntity);
    entityTransaction.commit();
    long appId = applicationEntity.getId();

    entityTransaction.begin();
    applicationEntity = this.entityManager.find(ApplicationEntity.class, appId);
    ApplicationKeyEntity applicationKeyEntity = new ApplicationKeyEntity(applicationEntity, "alias");
    ApplicationKeyEntity applicationKeyEntity2 = new ApplicationKeyEntity(applicationEntity, "alias2");
    this.entityManager.persist(applicationKeyEntity);
    this.entityManager.persist(applicationKeyEntity2);
    entityTransaction.commit();
    this.entityManager.close();

    this.entityManager = this.entityManagerFactory.createEntityManager();
    entityTransaction = this.entityManager.getTransaction();
    entityTransaction.begin();
    applicationKeyEntity = this.entityManager.find(ApplicationKeyEntity.class,
            new ApplicationKeyId(appId, "alias"));
    assertEquals("alias", applicationKeyEntity.getName());
    assertEquals("app", applicationKeyEntity.getApplication().getName());

    List<ApplicationKeyEntity> resultList = ApplicationKeyEntity.getApplicationKeys(this.entityManager,
            applicationEntity);
    assertEquals(2, resultList.size());
    for (ApplicationKeyEntity result : resultList) {
        LOG.debug("key: " + result.getName());
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default persist//from ww  w .j  av a2s  .c o m
 * 
 * @param obj
 *            object to persist
 * @throws PersistException
 *             on errors (transaction is being rolled back)
 */
public void persist(T obj) throws PersistException {
    if (obj == null) {
        return;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        em.persist(obj);
        t.commit();
    } catch (Exception e) {
        t.rollback();
        throw new PersistException(e.getMessage(), e);
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default merge/*from ww  w  .  j  ava2s  .com*/
 * 
 * @param obj
 *            object to merge
 * @throws MergeException
 *             on errors (transaction is being rolled back)
 * @return managed object
 */
public T merge(T obj) throws MergeException {
    if (obj == null) {
        return null;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        obj = em.merge(obj);
        t.commit();
        return obj;
    } catch (Exception e) {
        t.rollback();
        throw new MergeException("Cannot merge changes to " + String.valueOf(obj) + " into the database", e);
    }
}

From source file:nl.b3p.kaartenbalie.struts.KaartenbalieCrudAction.java

/** Execute method which handles all incoming request.
 *
 * @param mapping action mapping/*from  ww  w . ja  v a 2s  .  c  o  m*/
 * @param dynaForm dyna validator form
 * @param request servlet request
 * @param response servlet response
 *
 * @return ActionForward defined by Apache foundation
 *
 * @throws Exception
 */
// <editor-fold defaultstate="" desc="execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) method.">
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    Object identity = null;

    try {
        identity = MyEMFDatabase.createEntityManager(MyEMFDatabase.MAIN_EM);

        ActionForward forward = null;
        String msg = null;

        EntityManager em = getEntityManager();
        EntityTransaction tx = em.getTransaction();

        try {
            tx.begin();

            forward = super.execute(mapping, form, request, response);

            tx.commit();

            return forward;
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured, rollback", e);

            if (e instanceof org.hibernate.JDBCException) {
                msg = e.toString();
                SQLException sqle = ((org.hibernate.JDBCException) e).getSQLException();
                msg = msg + ": " + sqle;
                SQLException nextSqlE = sqle.getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else if (e instanceof java.sql.SQLException) {
                msg = e.toString();
                SQLException nextSqlE = ((java.sql.SQLException) e).getNextException();
                if (nextSqlE != null) {
                    msg = msg + ": " + nextSqlE;
                }
            } else {
                msg = e.toString();
            }

            addAlternateMessage(mapping, request, null, msg);
        }

        try {
            tx.begin();

            prepareMethod((DynaValidatorForm) form, request, LIST, EDIT);

            tx.commit();
        } catch (Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }

            log.error("Exception occured in second session, rollback", e);

            addAlternateMessage(mapping, request, null, e.toString());
        }
    } catch (Throwable e) {
        log.error("Exception occured while getting EntityManager: ", e);
        addAlternateMessage(mapping, request, null, e.toString());

    } finally {
        log.debug("Closing entity manager .....");
        MyEMFDatabase.closeEntityManager(identity, MyEMFDatabase.MAIN_EM);
    }

    return getAlternateForward(mapping, request);
}

From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java

/**
 * {@inheritDoc}/*from   www.j av a  2  s.  co  m*/
 */
@Override
public void saveUser(User user) {
    EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf))
            .getEntityManager();
    EntityTransaction tx = em.getTransaction();
    if (!tx.isActive()) {
        tx.begin();
    }
    em.persist(user);
    tx.commit();
}

From source file:org.easy.criteria.BaseDAO.java

/**
 * {@link javax.persistence.EntityTransaction#isActive())}
 *  {@link javax.persistence.EntityTransaction#commit())}
 *//*  ww  w  .  j  a  v  a 2  s  .com*/
public void commitTransaction(EntityTransaction transaction) {
    if (transaction.isActive())
        transaction.commit();
}

From source file:com.appdynamicspilot.persistence.BasePersistenceImpl.java

/**
 * The method to update the serailizable business objects into the database.
 * //  www  . jav  a  2s.com
 * @param object --
 *            serializable object
 * @throws PersistenceException
 */
@Transactional
public void update(final Serializable object) {
    EntityManager entityManager = getEntityManager();
    EntityTransaction txn = entityManager.getTransaction();
    txn.begin();
    try {
        entityManager.merge(object);
    } catch (Exception ex) {
        logger.error(ex);
        txn.rollback();
    } finally {
        if (!txn.getRollbackOnly()) {
            txn.commit();
        }
    }
}

From source file:com.appdynamicspilot.persistence.BasePersistenceImpl.java

@Transactional
public void delete(Serializable object) {
    EntityManager entityManager = getEntityManager();
    EntityTransaction txn = entityManager.getTransaction();
    txn.begin();/*w  w  w .j a  v  a2  s .  c om*/
    try {
        entityManager.remove(object);
    } catch (Exception ex) {
        logger.error(ex);
        txn.rollback();
    } finally {
        if (!txn.getRollbackOnly()) {
            txn.commit();
        }
    }
}