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:br.com.blackhouse.internet.bindings.intercept.TransactionalInterceptor.java

@AroundInvoke
public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction transaction = entityManager.getTransaction();

    try {/*w  w w  . j  av a 2 s . com*/
        if (!transaction.isActive()) {
            transaction.begin();
        }

        return context.proceed();

    } catch (Exception e) {
        logger.error("Exception in transactional method call", e);

        if (transaction != null) {
            transaction.rollback();
        }

        throw e;

    } finally {
        if (transaction != null && transaction.isActive()) {
            transaction.commit();
        }
    }

}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * A utility class to load the user directory.
 * /*from  w ww  .  j  a  v  a 2s .c o m*/
 * @param user
 *          the user object
 */
public void addUser(JpaUser user) {

    // Create a JPA user with an encoded password.
    String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles());

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(user);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java

/**
 * {@inheritDoc}/*w  w w.  j  av a  2  s .  c  o m*/
 *
 * @see org.eclipse.smila.binarystorage.internal.impl.persistence.BinaryPersistence#deleteBinary(java.lang.String)
 */
@Override
public void deleteBinary(final String key) throws BinaryStorageException {
    if (key == null) {
        throw new BinaryStorageException("parameter key is null");
    }
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final BinaryStorageDao dao = findBinaryStorageDao(em, key);
            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 BinaryStorageException(e, "error removing record id: " + key);
                }
            } else {
                if (_log.isDebugEnabled()) {
                    _log.debug("could not remove id: " + key + ". no binary object with this id exists.");
                }
            }
        } finally {
            closeEntityManager(em);
        }
    } finally {
        _lock.readLock().unlock();
    }
}

From source file:test.unit.be.fedict.eid.applet.beta.PersistenceTest.java

@After
public void tearDown() throws Exception {
    EntityTransaction entityTransaction = this.entityManager.getTransaction();
    LOG.debug("entity manager open: " + this.entityManager.isOpen());
    LOG.debug("entity transaction active: " + entityTransaction.isActive());
    if (entityTransaction.isActive()) {
        if (entityTransaction.getRollbackOnly()) {
            entityTransaction.rollback();
        } else {/* w  ww  . jav a 2  s .  c  o  m*/
            entityTransaction.commit();
        }
    }
    this.entityManager.close();
}

From source file:com.google.inject.persist.jpa.KuneJpaLocalTxnInterceptor.java

@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable, DefaultException {

    // Should we start a unit of work?
    if (!emProvider.isWorking()) {
        emProvider.begin();//w  w w.j  a  va  2s.c  o  m
        didWeStartWork.set(true);
        LOG.debug("Starting transaction");
    }

    final KuneTransactional transactional = readTransactionMetadata(methodInvocation);
    final EntityManager em = this.emProvider.get();

    // Allow 'joining' of transactions if there is an enclosing
    // @KuneTransactional method.
    if (em.getTransaction().isActive()) {
        LOG.debug("Joining a previous transaction");
        return methodInvocation.proceed();
    }

    final EntityTransaction txn = em.getTransaction();
    txn.begin();

    Object result;
    try {
        result = methodInvocation.proceed();

    } catch (final Exception e) {
        // commit transaction only if rollback didnt occur
        LOG.debug("Exception in transaction", e);
        if (rollbackIfNecessary(transactional, e, txn)) {
            txn.commit();
        }

        // propagate whatever exception is thrown anyway
        throw e;
    } finally {
        // Close the em if necessary (guarded so this code doesn't run unless
        // catch fired).
        if (null != didWeStartWork.get() && !txn.isActive()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // everything was normal so commit the txn (do not move into try block above
    // as it
    // interferes with the advised method's throwing semantics)
    try {
        LOG.debug("Trying to commit transaction");
        txn.commit();
    } finally {
        LOG.debug("Transaction commited");
        // close the em if necessary
        if (null != didWeStartWork.get()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // or return result
    return result;
}

From source file:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testClearCache() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager entityManager = emf.createEntityManager();
    EntityTransaction tx = entityManager.getTransaction();
    tx.begin();/*from   w  w  w.  ja  v  a2s.  co  m*/
    SubQObject subQObject = new SubQObject("one", "two");
    QObject qObject = new QObject("one");
    PObject pObject = new PObject("one");
    entityManager.persist(subQObject);
    entityManager.persist(qObject);
    entityManager.persist(pObject);
    tx.commit();
    assertTrue(getCache(subQObject.getClass()).contains(getOpenJPAId(subQObject, subQObject.getId())));
    assertTrue(getCache(qObject.getClass()).contains(getOpenJPAId(qObject, qObject.getId())));
    assertTrue(getCache(pObject.getClass()).contains(getOpenJPAId(pObject, pObject.getId())));
    evictAllOfType(qObject.getClass(), false);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("two");
    entityManager.persist(qObject);
    tx.commit();
    evictAllOfType(qObject.getClass(), true);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("three");
    entityManager.persist(qObject);
    subQObject = new SubQObject("two", "two");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(subQObject.getClass(), false);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    subQObject = new SubQObject("three", "three");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(pObject.getClass(), true);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertFalse("This PObject object should be gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
}

From source file:com.eucalyptus.images.Images.java

private static PutGetImageInfo persistRegistration(UserFullName creator, ImageManifest manifest,
        PutGetImageInfo ret) throws Exception {

    EntityTransaction tx = Entities.get(PutGetImageInfo.class);
    try {/*from  ww  w . jav  a 2 s  .  c  o  m*/
        ret = Entities.merge(ret);
        tx.commit();
        LOG.info("Registering image pk=" + ret.getDisplayName() + " ownerId=" + creator);
    } catch (Exception e) {
        tx.rollback();
        throw new EucalyptusCloudException(
                "Failed to register image: " + manifest + " because of: " + e.getMessage(), e);
    }
    // TODO:GRZE:RESTORE
    // for( String p : extractProductCodes( inputSource, xpath ) ) {
    // imageInfo.addProductCode( p );
    // }
    // imageInfo.grantPermission( ctx.getAccount( ) );
    LOG.info("Triggering cache population in Walrus for: " + ret.getDisplayName());
    if (ret instanceof ImageMetadata.StaticDiskImage && ret.getRunManifestLocation() != null) {
        StaticDiskImages.prepare(ret.getRunManifestLocation());
    }
    return ret;
}

From source file:org.apache.openjpa.persistence.event.TestBeforeCommit.java

public void testQuery() {
    OpenJPAEntityManagerSPI em = (OpenJPAEntityManagerSPI) emf.createEntityManager();
    em.addTransactionListener(this);
    EntityTransaction tran = em.getTransaction();

    tran.begin();//from w  w  w.java2s.c  o  m
    ae = doQuery(em);
    if (dict instanceof OracleDictionary) {
        assertNull(ae.getName());
    } else if (dict instanceof SybaseDictionary) {
        // Sybase converts empty strings to " " 
        assertEquals(" ", ae.getName());
    } else {
        assertEquals("", ae.getName());
    }
    assertEquals(1, ae.getVersion());
    tran.commit();

    ae = doQuery(em);
    assertEquals("Ava", ae.getName());
    assertEquals(2, ae.getVersion());

    em.clear();
    ae = em.find(AnEntity.class, PKID);
    assertEquals("Ava", ae.getName());
    assertEquals(2, ae.getVersion());

    tran.begin();
    tran.commit();
    em.clear();
    ae = em.find(AnEntity.class, PKID);
    assertEquals("AvaAva", ae.getName());
    assertEquals(3, ae.getVersion());

    em.close();
}

From source file:org.apache.openjpa.persistence.event.TestBeforeCommit.java

public void testEmptyTransaction() {
    OpenJPAEntityManagerSPI em = (OpenJPAEntityManagerSPI) emf.createEntityManager();
    em.addTransactionListener(this);
    EntityTransaction tran = em.getTransaction();
    ae = doQuery(em);/* w w  w.  ja  v  a  2 s.c o m*/
    if (dict instanceof OracleDictionary) {
        assertNull(ae.getName());
    } else if (dict instanceof SybaseDictionary) {
        // Sybase converts "" to " "
        assertEquals(" ", ae.getName());
    } else {
        assertEquals("", ae.getName());
    }
    assertEquals(1, ae.getVersion());
    em.clear();

    tran.begin();
    tran.commit();

    // when BeforeCommit was fired AE was not managed. As a result its state is out of sync with the database.
    assertEquals("Ava", ae.getName());
    ae = doQuery(em);
    if (dict instanceof OracleDictionary) {
        assertNull(ae.getName());
    } else if (dict instanceof SybaseDictionary) {
        assertEquals(" ", ae.getName());
    } else {
        assertEquals("", ae.getName());
    }
    assertEquals(1, ae.getVersion());
    em.close();
}

From source file:com.github.jinahya.persistence.ShadowTest.java

@Test(enabled = false, invocationCount = 1)
public void testPuthenticate() {
    final EntityManager manager = LocalPU.createEntityManager();
    try {/*from ww w.  j a v  a  2 s . c om*/
        final EntityTransaction transaction = manager.getTransaction();
        transaction.begin();
        try {
            final String username = newUsername(manager);
            final byte[] password = newPassword();

            final Shadow shadow = persistInstance(manager, username, password);

            Assert.assertTrue(shadow.puthenticate(shadow, password));

            transaction.commit();
        } catch (Exception e) {
            LocalPU.printConstraintViolation(e);
            transaction.rollback();
            e.printStackTrace(System.err);
            Assert.fail(e.getMessage());
        }
    } finally {
        manager.close();
    }
}