Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:it.infn.ct.futuregateway.apiserver.resources.observers.TaskObserver.java

@Override
public final void update(final Observable obs, final Object arg) {
    if (!(obs instanceof Task)) {
        log.error("Wrong abject associated with the oserver");
    }// w  w  w  . j  a  va  2 s  .  c  o  m
    Task t = (Task) obs;
    if (t.getId() == null || t.getStatus() == null) {
        return;
    }
    log.debug("Task " + t.getId() + " updated");
    if (t.getStatus().equals(Task.STATUS.WAITING) && t.getApplicationDetail() != null) {
        if (t.getInputFiles() != null) {
            for (TaskFile tf : t.getInputFiles()) {
                if (tf.getStatus().equals(TaskFile.FILESTATUS.NEEDED)) {
                    return;
                }
            }
        }
        t.setStatus(Task.STATUS.READY);
        submit(t);
    }
    EntityManager em = emf.createEntityManager();
    EntityTransaction et = em.getTransaction();
    try {
        et.begin();
        em.merge(t);
        et.commit();
    } catch (RuntimeException re) {
        log.error("Impossible to update the task!");
        log.error(re);
        if (et != null && et.isActive()) {
            et.rollback();
        }
    } finally {
        em.close();
    }
}

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

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

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

@Transactional
public void deleteAllCartItems(Long userId) {
    EntityManager em = getEntityManager();
    EntityTransaction txn = em.getTransaction();
    txn.begin();/*from   w w  w  .  ja  v  a  2  s .c o m*/
    Query q = em.createQuery("DELETE FROM Cart c where c.user.id=:id");
    q.setParameter("id", userId);
    q.executeUpdate();
    txn.commit();
}

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

/**
 * The method to update the serailizable business objects into the database.
 * //from   w  ww  .  ja  v a 2s  .  c o m
 * @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 save(final Serializable object) {
    EntityManager entityManager = getEntityManager();
    EntityTransaction txn = entityManager.getTransaction();
    txn.begin();//from  ww w.java2  s . c om
    try {
        entityManager.persist(object);
    } catch (Exception ex) {
        logger.error(ex);
        txn.rollback();
    } finally {
        if (!txn.getRollbackOnly()) {
            txn.commit();
        }
    }

}

From source file:com.epam.training.taranovski.web.project.repository.implementation.UserSkillRepositoryImplementation.java

@Override
public UserSkill getById(int id) {
    EntityManager em = entityManagerFactory.createEntityManager();
    UserSkill userSkill;//w  w  w . ja v  a2  s.  co m
    try {
        em.getTransaction().begin();
        userSkill = em.find(UserSkill.class, id);
        em.getTransaction().commit();
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return userSkill;
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public Object create(ODataUri uri, Object entity, EntityDataModel entityDataModel) throws ODataException {
    Object jpaEntity = entityMapper.convertODataEntityToDS(entity, entityDataModel);
    EntityManager entityManager = getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {/* w  ww  .ja va  2 s.com*/
        transaction.begin();

        LOG.info("Persisting entity: {}", jpaEntity);
        entityManager.persist(jpaEntity);

        return entityMapper.convertDSEntityToOData(jpaEntity, entity.getClass(), entityDataModel);
    } finally {
        if (transaction.isActive()) {
            transaction.commit();
        } else {
            transaction.rollback();
        }
    }
}

From source file:controllers.AuthController.java

@UnitOfWork
@FilterWith(CTCheck.class)
public Result signup(Context context, Session session, @JSR303Validation User u, Validation validation) {
    if (validation.hasBeanViolations()) {
        ArrayList map = new ArrayList();
        for (Iterator<FieldViolation> i = validation.getBeanViolations().listIterator(); i.hasNext();) {
            FieldViolation elem = i.next();
            map.add(elem.field + " " + elem.constraintViolation.getMessageKey());
        }/*from  w w w . j  ava2s.  c o m*/
        return Results.json().status(400).render(new JSendResp(400, map));
    }

    try {
        EntityManager entitymanager = entitiyManagerProvider.get();
        entitymanager.getTransaction().begin();
        entitymanager.persist(u);
        entitymanager.getTransaction().commit();
        String token = SessionIdentifierGenerator.nextSessionId();
        context.addCookie(Cookie.builder("token", token).build());
        ninjaCache.set(token, u.getId());
        session.put("token", token);
        session.put("email", u.getEmail());
        session.put("id", String.valueOf(u.getId()));
        return Results.json().render(new RespAuth(u.getId(), token, u.getEmail()));
    } catch (Exception e) {
        return Results.json().status(400).render(new JSendResp(400, e));
    }
}

From source file:com.pocketgorilla.stripesem.TransactionFilter.java

private void doAfter() {
    EntityManager em = provider.getEntityManager(false);
    if ((em != null) && (em.isOpen())) {
        EntityTransaction tx = em.getTransaction();
        if (tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();/* w w  w  . java  2s  . co m*/
                log.info("Rolled back persistence transaction.");
            } else {
                tx.commit();
                log.debug("Committed persistence transaction.");
            }
        }
        em.close();
        provider.removeEntityManager();
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.UserSkillRepositoryImplementation.java

@Override
public boolean create(UserSkill userSkill) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from w w  w.  j a  va2  s  .co  m*/
        em.getTransaction().begin();
        em.persist(userSkill);
        em.getTransaction().commit();
        success = true;
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}