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:org.debux.webmotion.jpa.Transactional.java

/**
 * Create the transaction and the GenericDAO if the entity name is not 
 * empty or null./* w ww .  j  a  v  a 2  s  .  c  o  m*/
 * 
 * @param request set EntityManager, EntityTransaction and GenericDAO into the request
 * @param persistenceUnitName precise the persistence unit
 * @param packageEntityName precise the package of entity
 * @param entityName precise the class name of the entity
 * 
 * @throws Exception catch execption to rollback the transaction
 */
public void tx(HttpServletRequest request, String persistenceUnitName, Properties properties,
        String packageEntityName, String entityName) throws Exception {

    // Create factory
    if (persistenceUnitName == null || persistenceUnitName.isEmpty()) {
        persistenceUnitName = DEFAULT_PERSISTENCE_UNIT_NAME;
    }
    EntityManagerFactory factory = factories.get(persistenceUnitName);
    if (factory == null) {
        Configuration subset = properties.subset(persistenceUnitName);
        java.util.Properties additionalProperties = ConfigurationConverter.getProperties(subset);

        factory = Persistence.createEntityManagerFactory(persistenceUnitName, additionalProperties);
        factories.put(persistenceUnitName, factory);
    }

    // Create manager
    EntityManager manager = (EntityManager) request.getAttribute(CURRENT_ENTITY_MANAGER);
    if (manager == null) {
        manager = factory.createEntityManager();
        request.setAttribute(CURRENT_ENTITY_MANAGER, manager);
    }

    // Create generic DAO each time if callback an action on an other entity
    if (entityName != null) {
        String fullEntityName = null;
        if (packageEntityName != null && !packageEntityName.isEmpty()) {
            fullEntityName = packageEntityName + "." + entityName;
        } else {
            fullEntityName = entityName;
        }

        GenericDAO genericDAO = new GenericDAO(manager, fullEntityName);
        request.setAttribute(CURRENT_GENERIC_DAO, genericDAO);

    } else {
        request.setAttribute(CURRENT_GENERIC_DAO, null);
    }

    // Create transaction
    EntityTransaction transaction = (EntityTransaction) request.getAttribute(CURRENT_ENTITY_TRANSACTION);
    if (transaction == null) {
        transaction = manager.getTransaction();
        request.setAttribute(CURRENT_ENTITY_TRANSACTION, transaction);

        transaction.begin();

        try {
            doProcess();
        } catch (Exception e) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
            throw e;
        }

        if (transaction.isActive()) {
            transaction.commit();
        }
        manager.close();

    } else {
        doProcess();
    }
}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

@Override
public void deleteTheme(long id) throws ThemesServiceDatabaseException, NotFoundException {
    EntityManager em = null;/*from   w w w .  java 2 s .  c  o m*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        ThemeDto themeDto = getThemeDto(id, em);
        if (themeDto == null)
            throw new NotFoundException("No theme with id=" + id + " exists");

        tx = em.getTransaction();
        tx.begin();
        em.remove(themeDto);
        tx.commit();
        messageSender.sendObjectMessage(ThemeItem.THEME_QUEUE, MessageSender.DestinationType.Queue,
                ThemeItem.delete(id));
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        logger.error("Could not delete theme '{}': {}", id, ExceptionUtils.getStackTrace(e));
        if (tx.isActive())
            tx.rollback();
        throw new ThemesServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.sakaiproject.kernel.social.FriendsListener.java

/**
 * {@inheritDoc}//  w w w. ja v  a  2s  . c  o m
 *
 * @see org.sakaiproject.kernel.jcr.api.JcrContentListener#onEvent(int,
 *      java.lang.String, java.lang.String, java.lang.String)
 */
public void onEvent(int type, String userID, String filePath, String fileName) {
    if (filePath.startsWith(privatePathBase)) {
        System.err.println("++++++++++++++++++++++++++ Checking event matches " + fileName + " "
                + KernelConstants.FRIENDS_FILE + " " + fileName.equals(KernelConstants.FRIENDS_FILE));
        if (fileName.equals(KernelConstants.FRIENDS_FILE)) {
            String friendsBody = null;
            InputStream in = null;
            try {
                in = jcrNodeFactoryService.getInputStream(filePath);
                friendsBody = IOUtils.readFully(in, "UTF-8");
                if (friendsBody != null && friendsBody.length() > 0) {
                    System.err.println("Converting " + friendsBody + " to Bean");
                    FriendsBean friendsBean = beanConverter.convertToObject(friendsBody, FriendsBean.class);

                    Query query = entityManager.createNamedQuery(FriendsIndexBean.FINDBY_UUID);
                    query.setParameter(FriendsIndexBean.PARAM_UUID, friendsBean.getUuid());
                    List<?> friendsIndexBeanList = query.getResultList();
                    List<FriendsIndexBean> toAdd = Lists.newArrayList();
                    List<FriendsIndexBean> toRemove = Lists.newArrayList();
                    List<FriendsIndexBean> toUpdate = Lists.newArrayList();

                    for (Object o : friendsIndexBeanList) {
                        FriendsIndexBean friendIndexBean = (FriendsIndexBean) o;
                        if (!friendsBean.hasFriend(friendIndexBean.getFriendUuid())) {
                            toRemove.add(friendIndexBean);
                        }
                    }

                    for (FriendBean friendBean : friendsBean.getFriends()) {
                        boolean found = false;
                        String newFriendUuid = friendBean.getFriendUuid();
                        for (Object o : friendsIndexBeanList) {
                            FriendsIndexBean friendIndexBean = (FriendsIndexBean) o;
                            String friendUuid = friendIndexBean.getFriendUuid();
                            if (newFriendUuid.equals(friendUuid)) {
                                found = true;
                                if (friendBean.getLastUpdate() > friendIndexBean.getLastUpdate()) {
                                    UserProfile userProfile = profileResolverService.resolve(friendUuid);
                                    friendIndexBean.copy(friendBean, userProfile);

                                    toUpdate.add(friendIndexBean);
                                }
                                break;
                            }
                        }
                        if (!found) {
                            UserProfile userProfile = profileResolverService.resolve(newFriendUuid);
                            toAdd.add(new FriendsIndexBean(friendBean, userProfile));
                        }
                    }

                    EntityTransaction transaction = entityManager.getTransaction();
                    transaction.begin();
                    for (FriendsIndexBean gm : toRemove) {
                        entityManager.remove(gm);
                    }
                    for (FriendsIndexBean gm : toAdd) {
                        entityManager.persist(gm);
                    }
                    for (FriendsIndexBean gm : toUpdate) {
                        entityManager.persist(gm);
                    }
                    transaction.commit();
                }

            } catch (UnsupportedEncodingException e) {
                LOG.error(e);
            } catch (IOException e) {
                LOG.warn("Failed to read userenv " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (RepositoryException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } catch (JCRNodeFactoryServiceException e) {
                LOG.warn("Failed to read userenv for " + filePath + " cause :" + e.getMessage());
                if (debug)
                    LOG.debug(e);
            } finally {
                try {
                    in.close();
                } catch (Exception ex) {
                }
            }
        }
    }
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * // w ww. j  a  v  a2  s. c  o m
 * @param em
 *            entity manager
 * @throws PersistenceException
 *             if we blow up
 */
private static void createOrUpdateDBVersion(EntityManager em) throws PersistenceException {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        try {
            DBVersionPO version = (DBVersionPO) em.createQuery("select version from DBVersionPO as version") //$NON-NLS-1$
                    .getSingleResult();
            version.setMajorVersion(IVersion.JB_DB_MAJOR_VERSION);
            version.setMinorVersion(IVersion.JB_DB_MINOR_VERSION);
            em.merge(version);
        } catch (NoResultException nre) {
            em.merge(new DBVersionPO(IVersion.JB_DB_MAJOR_VERSION, IVersion.JB_DB_MINOR_VERSION));
        }

        tx.commit();
    } catch (PersistenceException pe) {
        if (tx != null) {
            tx.rollback();
        }
        throw pe;
    }
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void deleteEvent(long eventId) throws NotFoundException, SchedulerServiceDatabaseException {
    EntityManager em = null;/*from  w  w w  .  ja v a 2  s . c om*/
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist");
        }
        em.remove(entity);
        tx.commit();
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (e instanceof NotFoundException) {
            throw (NotFoundException) e;
        }
        logger.error("Could not delete series: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.sigmah.server.dao.hibernate.TransactionalInterceptor.java

@Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    EntityManager em = injector.getInstance(EntityManager.class);
    EntityTransaction tx = em.getTransaction();

    //allow joining of transactions if there is an enclosing @Transactional method
    if (tx.isActive()) {

        if (log.isDebugEnabled()) {
            log.debug("[invoke] Transaction already active, just proceed the method.");
        }//from   ww w  .ja  va 2s .  c  om

        return methodInvocation.proceed();
    }

    tx.begin();

    if (log.isDebugEnabled()) {
        log.debug("[invoke] Begins an entity transaction.");
    }

    Object result = attemptInvocation(methodInvocation, tx);

    // everything was normal so commit the txn (do not move into try block as it interferes
    // with the advised method's throwing semantics)
    tx.commit();

    if (log.isDebugEnabled()) {
        log.debug("[invoke] Commits the transaction.");
    }

    return result;
}

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

/**
 * Removes the infrastructure. Delete the infrastructure only if there are
 * not applications associated with it to avoid inconsistency in the DB.
 * <p>/*from   w  w w .  j  a v  a2  s  .com*/
 * Infrastructures with associated applications can only be disabled to
 * avoid future execution of applications.
 *
 * @param id Id of the infrastructure to remove
 */
@DELETE
public final void deleteInfra(@PathParam("id") final String id) {
    Infrastructure infra;
    EntityManager em = getEntityManager();
    try {
        infra = em.find(Infrastructure.class, id);
        if (infra == null) {
            throw new NotFoundException();
        }
        EntityTransaction et = em.getTransaction();
        try {
            et.begin();
            List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure")
                    .setParameter("infraId", id).setMaxResults(1).getResultList();
            if (appsForInfra == null || appsForInfra.isEmpty()) {
                em.remove(infra);
            } else {
                throw new WebApplicationException("The infrastructure "
                        + "cannot be removed because there are associated " + "applications",
                        Response.Status.CONFLICT);
            }
            et.commit();
        } catch (WebApplicationException wex) {
            throw wex;
        } catch (RuntimeException re) {
            log.error(re);
            log.error("Impossible to remove the infrastructure");
            throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id);
        } finally {
            if (et != null && et.isActive()) {
                et.rollback();
            }
        }
    } catch (IllegalArgumentException re) {
        log.error("Impossible to retrieve the infrastructure list");
        log.error(re);
        throw new BadRequestException("Task '" + id + "' does not exist!");
    } finally {
        em.close();
    }
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

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

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*from www . j  a  va 2s  .  co m*/

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

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

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

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*  w  ww .ja  v  a  2 s  .com*/

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

    entityTransaction.commit();

}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

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

    EntityTransaction entityTransaction = entityManager.getTransaction();

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

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

    entityTransaction.commit();

}