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: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 {/*from www  .j  a v  a2 s.co  m*/
        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:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * @see/*from  w w w .j  ava  2s  .  c  om*/
 * org.apache.james.user.lib.AbstractUsersRepository#doAddUser(java.lang.String, java.lang.String)
 */
protected void doAddUser(String username, String password) throws UsersRepositoryException {
    String lowerCasedUsername = username.toLowerCase();
    if (contains(lowerCasedUsername)) {
        throw new UsersRepositoryException(lowerCasedUsername + " already exists.");
    }
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        JPAUser user = new JPAUser(lowerCasedUsername, password, algo);
        entityManager.persist(user);
        transaction.commit();
    } catch (PersistenceException e) {
        getLogger().debug("Failed to save user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to add user" + username, e);
    } finally {
        entityManager.close();
    }
}

From source file:com.eucalyptus.objectstorage.entities.upgrade.ObjectStorage400Upgrade.java

private static void populateSnapshotBucketsAndObjects() {
    EntityTransaction tran = Entities.get(WalrusSnapshotInfo.class);
    try {//from   w  w  w  .  j  a  v  a  2s  . co  m
        List<WalrusSnapshotInfo> walrusSnapshots = Entities.query(new WalrusSnapshotInfo(), Boolean.TRUE);
        for (WalrusSnapshotInfo walrusSnapshot : walrusSnapshots) {
            walrusSnapshotBuckets.add(walrusSnapshot.getSnapshotBucket());
            walrusSnapshotObjects.add(walrusSnapshot.getSnapshotId());
        }
        tran.commit();
    } catch (Exception e) {
        LOG.error("Failed to lookup snapshots stored in Walrus", e);
        tran.rollback();
        throw e;
    } finally {
        if (tran.isActive()) {
            tran.commit();
        }
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Removes a user from the repository//  www. j av  a2s  . c  o  m
 * 
 * @param name
 *            the user to remove from the repository
 * @throws UsersRepositoryException
 */
public void removeUser(String name) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        if (entityManager.createNamedQuery("deleteUserByName").setParameter("name", name).executeUpdate() < 1) {
            transaction.commit();
            throw new UsersRepositoryException("User " + name + " does not exist");
        } else {
            transaction.commit();
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to remove user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to remove user " + name, e);
    } finally {
        entityManager.close();
    }
}

From source file:name.livitski.tools.persista.schema.example.CustomerCRUDTest.java

@Test
public void testUpdateDelete() {
    assertNotNull("stored object must have a positive id, got null", storedRecordId);
    final Log log = log();
    final EntityManager db = getEntityManager();
    final EntityTransaction txn = db.getTransaction();
    txn.begin();/* w w w.j a  v a 2 s  .  c o  m*/
    Customer customer = db.find(Customer.class, storedRecordId);
    assertNotNull("cannot find record of type " + Customer.class + " with id=" + storedRecordId, customer);
    customer.setName(UPDATED_NAME);
    customer.setAddress(UPDATED_ADDRESS);
    customer.setPhone(UPDATED_PHONE);
    customer.setEmail(UPDATED_EMAIL);
    txn.commit();
    log.info("Updated customer record with id=" + storedRecordId);
    expected = new String[] { UPDATED_NAME, UPDATED_ADDRESS, UPDATED_PHONE, UPDATED_EMAIL };
    testRead();
    txn.begin();
    db.refresh(customer);
    db.remove(customer);
    txn.commit();
    log.info("Deleted customer record with id=" + storedRecordId);
    customer = db.find(Customer.class, storedRecordId);
    assertNull("record of type " + Customer.class + " with id=" + storedRecordId + " was not deleted",
            customer);
    storedRecordId = null;
}

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

/**
 * Default remove: bring back to persistence context if required and delete
 * //from  w  ww .  j a v  a2s.c o  m
 * @param objs
 *            objects to remove
 * @return removed objects
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public Collection<T> remove(Collection<T> objs) throws Exception {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    Collection<T> res = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            T tmp = em.contains(obj) ? obj : em.merge(obj);
            em.remove(tmp);
            res.add(tmp);
        }
        t.commit();
        return res;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

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

/**
 * Register a new task./*w w  w . ja  v  a  2  s . c o m*/
 *
 * @param task The task to register
 * @return The task registered
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Task createTask(final Task task) {
    if (task.getApplicationId() == null) {
        throw new BadRequestException("A valid application for the task" + " must be provided");
    }
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    task.setDateCreated(new Date());
    task.setUserName(getUser());
    task.setStatus(Task.STATUS.WAITING);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        Application app = em.find(Application.class, task.getApplicationId());
        if (app == null) {
            throw new BadRequestException("Application id not valid");
        }
        task.setApplicationDetail(app);
        em.persist(task);
        et.commit();
        log.debug("New task registered: " + task.getId());
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        log.error("Impossible to create a task");
        log.debug(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return task;
}

From source file:nl.b3p.kaartenbalie.core.server.persistence.MyEMFDatabase.java

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);

    DataMonitoring/* w  w  w.ja va  2  s  .  com*/
            .setEnableMonitoring(getConfigValue(config, "reporting", "disabled").equalsIgnoreCase("enabled"));
    AccountManager
            .setEnableAccounting(getConfigValue(config, "accounting", "disabled").equalsIgnoreCase("enabled"));

    Object identity = null;
    try {
        openEntityManagerFactory(defaultKaartenbaliePU);
        identity = createEntityManager(MyEMFDatabase.INIT_EM);
        log.debug("Getting entity manager ......");
        EntityManager em = getEntityManager(MyEMFDatabase.INIT_EM);
        EntityTransaction tx = em.getTransaction();
        tx.begin();
        //            ReportGenerator.startupClear(em);
        tx.commit();
    } catch (Throwable e) {
        log.warn("Error creating EntityManager: ", e);
        throw new ServletException(e);
    } finally {
        log.debug("Closing entity manager .....");
        closeEntityManager(identity, MyEMFDatabase.INIT_EM);
    }

    cachePath = getConfigValue(config, "cache", "/");
    if (cachePath != null) {
        cachePath = getServletContext().getRealPath(cachePath);
        log.debug("cache pad: " + cachePath);
    }

    rg = new Random();

    String allowedUpload = config.getInitParameter("allowed_upload_files");
    if (allowedUpload != null && allowedUpload.length() > 0) {
        allowedUploadFiles = allowedUpload.split(",");
    }

    // load global context params
    initGlobalContextParams(config);

    // configure kb via properties
    KBConfiguration.configure();
}

From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java

/**
 * {@inheritDoc}/*w  w  w.  j a v  a  2 s.c om*/
 */
@Override
public void removeRecord(final String id) throws RecordStorageException {
    if (id == null) {
        throw new RecordStorageException("parameter id is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final RecordDao dao = findRecordDao(em, id);
            if (dao != null) {
                final EntityTransaction transaction = em.getTransaction();
                try {
                    transaction.begin();
                    em.remove(dao);
                    transaction.commit();
                } catch (final Exception e) {
                    if (transaction.isActive()) {
                        transaction.rollback();
                    }
                    throw new RecordStorageException(e, "error removing record id: " + id);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove record id: " + id + ". no record with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:org.apache.juddi.subscription.SubscriptionNotifier.java

/**
 * Deletes the subscription. i.e. when it is expired.
 * @param subscription//from  w w  w .  j  a v a  2 s.  c o  m
 */
protected void deleteSubscription(Subscription subscription) {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();
        em.remove(subscription);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}