Search in sources :

Example 76 with UserTransaction

use of javax.transaction.UserTransaction in project microservices by pwillhan.

the class NaturalPrimaryKey method storeLoad.

@Test
public void storeLoad() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            User user = new User("johndoe");
            em.persist(user);
        }
        tx.commit();
        em.close();
        tx.begin();
        em = JPA.createEntityManager();
        {
            User user = em.find(User.class, "johndoe");
            assertNotNull(user);
        }
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.complexschemas.naturalprimarykey.User) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 77 with UserTransaction

use of javax.transaction.UserTransaction in project microservices by pwillhan.

the class SecondaryTable method storeAndLoadUsers.

@Test
public void storeAndLoadUsers() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        User user = new User();
        user.setUsername("johndoe");
        Address homeAddress = new Address("Some Street 123", "12345", "Some City");
        user.setHomeAddress(homeAddress);
        em.persist(user);
        tx.commit();
        em.close();
        tx.begin();
        em = JPA.createEntityManager();
        User u = em.find(User.class, user.getId());
        assertEquals(u.getUsername(), "johndoe");
        assertEquals(u.getHomeAddress().getStreet(), "Some Street 123");
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.complexschemas.secondarytable.User) Address(org.jpwh.model.complexschemas.secondarytable.Address) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 78 with UserTransaction

use of javax.transaction.UserTransaction in project microservices by pwillhan.

the class Locking method findLock.

@Test
public void findLock() throws Exception {
    final ConcurrencyTestData testData = storeCategoriesAndItems();
    Long CATEGORY_ID = testData.categories.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        Map<String, Object> hints = new HashMap<String, Object>();
        hints.put("javax.persistence.lock.timeout", 5000);
        // Executes a SELECT .. FOR UPDATE WAIT 5000 if supported by dialect
        Category category = em.find(Category.class, CATEGORY_ID, LockModeType.PESSIMISTIC_WRITE, hints);
        category.setName("New Name");
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) EntityManager(javax.persistence.EntityManager) Category(org.jpwh.model.concurrency.version.Category) HashMap(java.util.HashMap) Test(org.testng.annotations.Test)

Example 79 with UserTransaction

use of javax.transaction.UserTransaction in project microservices by pwillhan.

the class NonTransactional method autoCommit.

// TODO: Broken on MySQL https://hibernate.atlassian.net/browse/HHH-8402
@Test(groups = { "H2", "ORACLE", "POSTGRESQL" })
public void autoCommit() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    Long ITEM_ID;
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        Item someItem = new Item("Original Name");
        em.persist(someItem);
        tx.commit();
        em.close();
        ITEM_ID = someItem.getId();
    } finally {
        TM.rollback();
    }
    {
        /* 
               No transaction is active when we create the <code>EntityManager</code>. The
               persistence context is now in a special <em>unsynchronized</em> mode, Hibernate
               will not flush automatically at any time.
             */
        EntityManager em = JPA.createEntityManager();
        /* 
               You can access the database to read data; this operation will execute a
               <code>SELECT</code> statement, sent to the database in auto-commit mode.
             */
        Item item = em.find(Item.class, ITEM_ID);
        item.setName("New Name");
        /* 
               Usually Hibernate would flush the persistence context when you execute a
               <code>Query</code>. However, because the context is <em>unsynchronized</em>,
               flushing will not occur and the query will return the old, original database
               value. Queries with scalar results are not repeatable, you'll see whatever
               values are present in the database and given to Hibernate in the
               <code>ResultSet</code>. Note that this isn't a repeatable read either if
               you are in <em>synchronized</em> mode.
             */
        assertEquals(em.createQuery("select i.name from Item i where i.id = :id)").setParameter("id", ITEM_ID).getSingleResult(), "Original Name");
        /* 
               Retrieving a managed entity instance involves a lookup, during JDBC
               result set marshaling, in the current persistence context. The
               already loaded <code>Item</code> instance with the changed name will
               be returned from the persistence context, values from the database
               will be ignored. This is a repeatable read of an entity instance,
               even without a system transaction.
             */
        assertEquals(((Item) em.createQuery("select i from Item i where i.id = :id)").setParameter("id", ITEM_ID).getSingleResult()).getName(), "New Name");
        /* 
               If you try to flush the persistence context manually, to store the new
               <code>Item#name</code>, Hibernate will throw a
               <code>javax.persistence.TransactionRequiredException</code>. You are
               prevented from executing an <code>UPDATE</code> statement in
               <em>unsynchronized</em> mode, as you wouldn't be able to roll back the change.
            */
        // em.flush();
        /* 
               You can roll back the change you made with the <code>refresh()</code>
               method, it loads the current <code>Item</code> state from the database
               and overwrites the change you have made in memory.
             */
        em.refresh(item);
        assertEquals(item.getName(), "Original Name");
        em.close();
    }
    {
        EntityManager em = JPA.createEntityManager();
        Item newItem = new Item("New Item");
        /* 
               You can call <code>persist()</code> to save a transient entity instance with an
               unsynchronized persistence context. Hibernate will only fetch a new identifier
               value, typically by calling a database sequence, and assign it to the instance.
               The instance is now in persistent state in the context but the SQL
               <code>INSERT</code> hasn't happened. Note that this is only possible with
               <em>pre-insert</em> identifier generators; see <a href="#GeneratorStrategies"/>.
            */
        em.persist(newItem);
        assertNotNull(newItem.getId());
        /* 
               When you are ready to store the changes, join the persistence context with
               a transaction. Synchronization and flushing will occur as usual, when the
               transaction commits. Hibernate writes all queued operations to the database.
             */
        tx.begin();
        if (!em.isJoinedToTransaction())
            em.joinTransaction();
        // Flush!
        tx.commit();
        em.close();
    }
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        assertEquals(em.find(Item.class, ITEM_ID).getName(), "Original Name");
        assertEquals(em.createQuery("select count(i) from Item i)").getSingleResult(), 2l);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
    {
        EntityManager tmp = JPA.createEntityManager();
        Item detachedItem = tmp.find(Item.class, ITEM_ID);
        tmp.close();
        detachedItem.setName("New Name");
        EntityManager em = JPA.createEntityManager();
        Item mergedItem = em.merge(detachedItem);
        tx.begin();
        em.joinTransaction();
        // Flush!
        tx.commit();
        em.close();
    }
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        assertEquals(em.find(Item.class, ITEM_ID).getName(), "New Name");
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
    {
        EntityManager em = JPA.createEntityManager();
        Item item = em.find(Item.class, ITEM_ID);
        em.remove(item);
        tx.begin();
        em.joinTransaction();
        // Flush!
        tx.commit();
        em.close();
    }
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        assertEquals(em.createQuery("select count(i) from Item i)").getSingleResult(), 1l);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.concurrency.version.Item) EntityManager(javax.persistence.EntityManager) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 80 with UserTransaction

use of javax.transaction.UserTransaction in project microservices by pwillhan.

the class Versioning method manualVersionChecking.

// TODO This throws the wrong exception!
// @Test(expectedExceptions = OptimisticLockException.class)
@Test(expectedExceptions = org.hibernate.OptimisticLockException.class)
public void manualVersionChecking() throws Throwable {
    final ConcurrencyTestData testData = storeCategoriesAndItems();
    Long[] CATEGORIES = testData.categories.identifiers;
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        BigDecimal totalPrice = new BigDecimal(0);
        for (Long categoryId : CATEGORIES) {
            /* 
                   For each <code>Category</code>, query all <code>Item</code> instances with
                   an <code>OPTIMISTIC</code> lock mode. Hibernate now knows it has to
                   check each <code>Item</code> at flush time.
                 */
            List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setLockMode(LockModeType.OPTIMISTIC).setParameter("catId", categoryId).getResultList();
            for (Item item : items) totalPrice = totalPrice.add(item.getBuyNowPrice());
            // Now a concurrent transaction will move an item to another category
            if (categoryId.equals(testData.categories.getFirstId())) {
                Executors.newSingleThreadExecutor().submit(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                        UserTransaction tx = TM.getUserTransaction();
                        try {
                            tx.begin();
                            EntityManager em = JPA.createEntityManager();
                            // Moving the first item from the first category into the last category
                            List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setParameter("catId", testData.categories.getFirstId()).getResultList();
                            Category lastCategory = em.getReference(Category.class, testData.categories.getLastId());
                            items.iterator().next().setCategory(lastCategory);
                            tx.commit();
                            em.close();
                        } catch (Exception ex) {
                            // This shouldn't happen, this commit should win!
                            TM.rollback();
                            throw new RuntimeException("Concurrent operation failure: " + ex, ex);
                        }
                        return null;
                    }
                }).get();
            }
        }
        /* 
               For each <code>Item</code> loaded earlier with the locking query, Hibernate will
               now execute a <code>SELECT</code> during flushing. It checks if the database
               version of each <code>ITEM</code> row is still the same as when it was loaded
               earlier. If any <code>ITEM</code> row has a different version, or the row doesn't
               exist anymore, an <code>OptimisticLockException</code> will be thrown.
             */
        tx.commit();
        em.close();
        assertEquals(totalPrice.toString(), "108.00");
    } catch (Exception ex) {
        throw unwrapCauseOfType(ex, org.hibernate.OptimisticLockException.class);
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Category(org.jpwh.model.concurrency.version.Category) OptimisticLockException(javax.persistence.OptimisticLockException) BigDecimal(java.math.BigDecimal) Callable(java.util.concurrent.Callable) OptimisticLockException(javax.persistence.OptimisticLockException) NoResultException(javax.persistence.NoResultException) InvalidBidException(org.jpwh.model.concurrency.version.InvalidBidException) Item(org.jpwh.model.concurrency.version.Item) EntityManager(javax.persistence.EntityManager) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Aggregations

UserTransaction (javax.transaction.UserTransaction)642 EntityManager (javax.persistence.EntityManager)244 Test (org.testng.annotations.Test)187 Test (org.junit.Test)157 JPATest (org.jpwh.env.JPATest)138 InitialContext (javax.naming.InitialContext)62 BigDecimal (java.math.BigDecimal)53 HashMap (java.util.HashMap)52 IOException (java.io.IOException)50 Context (javax.naming.Context)49 List (java.util.List)47 FacesContext (javax.faces.context.FacesContext)43 NamingException (javax.naming.NamingException)43 NodeRef (org.alfresco.service.cmr.repository.NodeRef)43 Node (javax.jcr.Node)42 KieSession (org.kie.api.runtime.KieSession)42 Query (javax.persistence.Query)38 QueryingTest (org.jpwh.test.querying.QueryingTest)36 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)35 Item (org.jpwh.model.querying.Item)35