Search in sources :

Example 1 with Item

use of org.jpwh.model.concurrency.version.Item 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 2 with Item

use of org.jpwh.model.concurrency.version.Item 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)

Example 3 with Item

use of org.jpwh.model.concurrency.version.Item in project microservices by pwillhan.

the class Locking method pessimisticReadWrite.

@Test
public void pessimisticReadWrite() throws Exception {
    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 in
                   <code>PESSIMISTIC_READ</code> lock mode. Hibernate will lock the rows in
                   the database with the SQL query. If possible, wait for 5 seconds if some
                   other transaction already holds a conflicting lock. If the lock can't
                   be obtained, the query throws an exception.
                 */
            List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setLockMode(LockModeType.PESSIMISTIC_READ).setHint("javax.persistence.lock.timeout", 5000).setParameter("catId", categoryId).getResultList();
            /* 
                   If the query returns successfully, you know that you hold an exclusive lock
                   on the data and no other transaction can access it with an exclusive lock or
                   modify it until this transaction commits.
                 */
            for (Item item : items) totalPrice = totalPrice.add(item.getBuyNowPrice());
            // read or write locks, only exclusive locks.
            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();
                            // connection/session.
                            if (TM.databaseProduct.equals(DatabaseProduct.POSTGRESQL)) {
                                em.unwrap(Session.class).doWork(new Work() {

                                    @Override
                                    public void execute(Connection connection) throws SQLException {
                                        connection.createStatement().execute("set statement_timeout = 5000");
                                    }
                                });
                            }
                            // can set a timeout for the whole connection/session.
                            if (TM.databaseProduct.equals(DatabaseProduct.MYSQL)) {
                                em.unwrap(Session.class).doWork(new Work() {

                                    @Override
                                    public void execute(Connection connection) throws SQLException {
                                        connection.createStatement().execute("set innodb_lock_wait_timeout = 5;");
                                    }
                                });
                            }
                            // Moving the first item from the first category into the last category
                            // This query should fail as someone else holds a lock on the rows.
                            List<Item> items = em.createQuery("select i from Item i where i.category.id = :catId").setParameter("catId", testData.categories.getFirstId()).setLockMode(// Prevent concurrent access
                            LockModeType.PESSIMISTIC_WRITE).setHint("javax.persistence.lock.timeout", // Only works on Oracle...
                            5000).getResultList();
                            Category lastCategory = em.getReference(Category.class, testData.categories.getLastId());
                            items.iterator().next().setCategory(lastCategory);
                            tx.commit();
                            em.close();
                        } catch (Exception ex) {
                            // This should fail, as the data is already locked!
                            TM.rollback();
                            if (TM.databaseProduct.equals(DatabaseProduct.POSTGRESQL)) {
                                // A statement timeout on PostgreSQL doesn't produce a specific exception
                                assertTrue(ex instanceof PersistenceException);
                            } else if (TM.databaseProduct.equals(DatabaseProduct.MYSQL)) {
                                // On MySQL we get a LockTimeoutException
                                assertTrue(ex instanceof LockTimeoutException);
                            } else {
                                // On H2 and Oracle we get a PessimisticLockException
                                assertTrue(ex instanceof PessimisticLockException);
                            }
                        }
                        return null;
                    }
                }).get();
            }
        }
        /* 
               Our locks will be released after commit, when the transaction completes.
             */
        tx.commit();
        em.close();
        assertEquals(totalPrice.compareTo(new BigDecimal("108")), 0);
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Category(org.jpwh.model.concurrency.version.Category) SQLException(java.sql.SQLException) Connection(java.sql.Connection) BigDecimal(java.math.BigDecimal) Callable(java.util.concurrent.Callable) LockTimeoutException(javax.persistence.LockTimeoutException) PessimisticLockException(javax.persistence.PessimisticLockException) SQLException(java.sql.SQLException) PersistenceException(javax.persistence.PersistenceException) PessimisticLockException(javax.persistence.PessimisticLockException) Item(org.jpwh.model.concurrency.version.Item) EntityManager(javax.persistence.EntityManager) Work(org.hibernate.jdbc.Work) PersistenceException(javax.persistence.PersistenceException) LockTimeoutException(javax.persistence.LockTimeoutException) Session(org.hibernate.Session) Test(org.testng.annotations.Test)

Example 4 with Item

use of org.jpwh.model.concurrency.version.Item in project microservices by pwillhan.

the class Locking method extendedLock.

// TODO: This test fails because nullable outer joined tuples can't be locked on Postgres
@Test(groups = { "H2", "MYSQL", "ORACLE" })
public void extendedLock() throws Exception {
    final ConcurrencyTestData testData = storeCategoriesAndItems();
    Long ITEM_ID = testData.items.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.scope", PessimisticLockScope.EXTENDED);
        Item item = em.find(Item.class, ITEM_ID, LockModeType.PESSIMISTIC_READ, hints);
        // TODO This query loading the images should lock the images rows, it doesn't.
        assertEquals(item.getImages().size(), 0);
        item.setName("New Name");
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.concurrency.version.Item) EntityManager(javax.persistence.EntityManager) HashMap(java.util.HashMap) Test(org.testng.annotations.Test)

Example 5 with Item

use of org.jpwh.model.concurrency.version.Item in project microservices by pwillhan.

the class Versioning method storeItemAndBids.

public TestData storeItemAndBids() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    tx.begin();
    EntityManager em = JPA.createEntityManager();
    Long[] ids = new Long[1];
    Item item = new Item("Some Item");
    em.persist(item);
    ids[0] = item.getId();
    for (int i = 1; i <= 3; i++) {
        Bid bid = new Bid(new BigDecimal(10 + i), item);
        em.persist(bid);
    }
    tx.commit();
    em.close();
    return new TestData(ids);
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.concurrency.version.Item) EntityManager(javax.persistence.EntityManager) TestData(org.jpwh.shared.util.TestData) Bid(org.jpwh.model.concurrency.version.Bid) BigDecimal(java.math.BigDecimal)

Aggregations

EntityManager (javax.persistence.EntityManager)8 UserTransaction (javax.transaction.UserTransaction)8 Item (org.jpwh.model.concurrency.version.Item)8 Test (org.testng.annotations.Test)6 BigDecimal (java.math.BigDecimal)5 Callable (java.util.concurrent.Callable)4 JPATest (org.jpwh.env.JPATest)4 NoResultException (javax.persistence.NoResultException)3 OptimisticLockException (javax.persistence.OptimisticLockException)3 Category (org.jpwh.model.concurrency.version.Category)3 InvalidBidException (org.jpwh.model.concurrency.version.InvalidBidException)3 TestData (org.jpwh.shared.util.TestData)3 Bid (org.jpwh.model.concurrency.version.Bid)2 Connection (java.sql.Connection)1 SQLException (java.sql.SQLException)1 HashMap (java.util.HashMap)1 LockTimeoutException (javax.persistence.LockTimeoutException)1 PersistenceException (javax.persistence.PersistenceException)1 PessimisticLockException (javax.persistence.PessimisticLockException)1 Session (org.hibernate.Session)1