Search in sources :

Example 71 with UserTransaction

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

the class BulkStatementsJPQL method bulkUpdateVersioned.

@Test
public void bulkUpdateVersioned() throws Exception {
    BulkBatchTestData testData = storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        long ITEM_ID = testData.items.getFirstId();
        Item someItem = em.find(Item.class, ITEM_ID);
        int originalVersion = someItem.getVersion();
        int updatedEntities = em.createQuery("update versioned Item i set i.active = true").executeUpdate();
        assertEquals(updatedEntities, 3);
        em.refresh(someItem);
        assertTrue(someItem.getVersion() > originalVersion);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.bulkbatch.Item) EntityManager(javax.persistence.EntityManager) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 72 with UserTransaction

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

the class BulkStatementsSQL method storeTestData.

public BulkBatchTestData storeTestData() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    tx.begin();
    EntityManager em = JPA.createEntityManager();
    Long[] itemIds = new Long[3];
    Long[] userIds = new Long[3];
    User johndoe = new User("johndoe");
    em.persist(johndoe);
    userIds[0] = johndoe.getId();
    User janeroe = new User("janeroe");
    em.persist(janeroe);
    userIds[1] = janeroe.getId();
    User robertdoe = new User("robertdoe");
    em.persist(robertdoe);
    userIds[2] = robertdoe.getId();
    Item item = new Item("Item One", CalendarUtil.TOMORROW.getTime(), johndoe);
    em.persist(item);
    itemIds[0] = item.getId();
    for (int i = 1; i <= 3; i++) {
        Bid bid = new Bid(item, robertdoe, new BigDecimal(9 + i));
        item.getBids().add(bid);
        em.persist(bid);
    }
    item = new Item("Item Two", CalendarUtil.TOMORROW.getTime(), johndoe);
    em.persist(item);
    itemIds[1] = item.getId();
    for (int i = 1; i <= 1; i++) {
        Bid bid = new Bid(item, janeroe, new BigDecimal(2 + i));
        item.getBids().add(bid);
        em.persist(bid);
    }
    item = new Item("Item_Three", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
    em.persist(item);
    itemIds[2] = item.getId();
    for (int i = 1; i <= 1; i++) {
        Bid bid = new Bid(item, johndoe, new BigDecimal(3 + i));
        item.getBids().add(bid);
        em.persist(bid);
    }
    em.persist(new BankAccount(janeroe, "Jane Roe", "445566", "One Percent Bank Inc.", "999"));
    em.persist(new CreditCard(johndoe, "John Doe", "1234123412341234", "06", "2015"));
    tx.commit();
    em.close();
    BulkBatchTestData testData = new BulkBatchTestData();
    testData.items = new TestData(itemIds);
    testData.users = new TestData(userIds);
    return testData;
}
Also used : UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.bulkbatch.User) TestData(org.jpwh.shared.util.TestData) BankAccount(org.jpwh.model.bulkbatch.BankAccount) BigDecimal(java.math.BigDecimal) CreditCard(org.jpwh.model.bulkbatch.CreditCard) StolenCreditCard(org.jpwh.model.bulkbatch.StolenCreditCard) Item(org.jpwh.model.bulkbatch.Item) EntityManager(javax.persistence.EntityManager) Bid(org.jpwh.model.bulkbatch.Bid)

Example 73 with UserTransaction

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

the class BulkStatementsSQL method bulkUpdateHibernate.

@Test(groups = { "H2", "MYSQL", "POSTGRESQL" })
public void bulkUpdateHibernate() throws Exception {
    BulkBatchTestData testData = storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        long ITEM_ID = testData.items.getFirstId();
        long USER_ID = testData.users.getFirstId();
        Item someItem = em.find(Item.class, ITEM_ID);
        User johndoe = em.find(User.class, USER_ID);
        int originalVersion = someItem.getVersion();
        assertEquals(someItem.getSeller(), johndoe);
        assertFalse(someItem.isActive());
        org.hibernate.SQLQuery query = em.unwrap(org.hibernate.Session.class).createSQLQuery("update ITEM set ACTIVE = true where SELLER_ID = :sellerId");
        query.setParameter("sellerId", johndoe.getId());
        query.addSynchronizedEntityClass(Item.class);
        // Only the second-level cache regions with Item data have been cleared
        int updatedEntities = query.executeUpdate();
        // Updated rows not entity instances!
        assertEquals(updatedEntities, 2);
        assertFalse(someItem.isActive());
        // Update the instance in persistence context
        em.refresh(someItem);
        assertTrue(someItem.isActive());
        // Version wasn't incremented!
        assertEquals(someItem.getVersion(), originalVersion);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.bulkbatch.Item) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.bulkbatch.User) JPATest(org.jpwh.env.JPATest) Test(org.testng.annotations.Test)

Example 74 with UserTransaction

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

the class SecondLevel method cacheBehavior.

@Test
public void cacheBehavior() throws Exception {
    CacheTestData testData = storeTestData();
    Long USER_ID = testData.users.getFirstId();
    Long ITEM_ID = testData.items.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        {
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            // Get the statistics API
            Statistics stats = JPA.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
            SecondLevelCacheStatistics itemCacheStats = stats.getSecondLevelCacheStatistics(Item.class.getName());
            assertEquals(itemCacheStats.getElementCountInMemory(), 3);
            assertEquals(itemCacheStats.getHitCount(), 0);
            // Hit the second-level cache with entity lookup by identifier
            Item item = em.find(Item.class, ITEM_ID);
            assertEquals(itemCacheStats.getHitCount(), 1);
            // Initializing a proxy will also hit the second-level cache
            SecondLevelCacheStatistics userCacheStats = stats.getSecondLevelCacheStatistics(User.class.getName());
            assertEquals(userCacheStats.getElementCountInMemory(), 3);
            assertEquals(userCacheStats.getHitCount(), 0);
            User seller = item.getSeller();
            // Initialize proxy
            assertEquals(seller.getUsername(), "johndoe");
            assertEquals(userCacheStats.getHitCount(), 1);
            // Get the Item#bids collection and its referenced Bid entity instances
            /* 
                   The statistics tell you that there are three <code>Item#bids</code>
                   collections in the cache (one for each <code>Item</code>). No
                   successful cache lookups have occurred so far.
                 */
            SecondLevelCacheStatistics bidsCacheStats = stats.getSecondLevelCacheStatistics(Item.class.getName() + ".bids");
            assertEquals(bidsCacheStats.getElementCountInMemory(), 3);
            assertEquals(bidsCacheStats.getHitCount(), 0);
            /* 
                   The entity cache of <code>Bid</code> has five records, and you
                   haven't accessed it either.
                 */
            SecondLevelCacheStatistics bidCacheStats = stats.getSecondLevelCacheStatistics(Bid.class.getName());
            assertEquals(bidCacheStats.getElementCountInMemory(), 5);
            assertEquals(bidCacheStats.getHitCount(), 0);
            /* 
                   Initializing the collection will read the data from both caches.
                 */
            Set<Bid> bids = item.getBids();
            assertEquals(bids.size(), 3);
            /* 
                   The cache found one collection, as well as the data for
                   its three <code>Bid</code> elements.
                 */
            assertEquals(bidsCacheStats.getHitCount(), 1);
            assertEquals(bidCacheStats.getHitCount(), 3);
            tx.commit();
            em.close();
        }
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.cache.Item) EntityManager(javax.persistence.EntityManager) User(org.jpwh.model.cache.User) Set(java.util.Set) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Statistics(org.hibernate.stat.Statistics) QueryStatistics(org.hibernate.stat.QueryStatistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) NaturalIdCacheStatistics(org.hibernate.stat.NaturalIdCacheStatistics) Test(org.testng.annotations.Test) JPATest(org.jpwh.env.JPATest)

Example 75 with UserTransaction

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

the class SecondLevel method cacheNaturalId.

@Test
public void cacheNaturalId() throws Exception {
    CacheTestData testData = storeTestData();
    Long USER_ID = testData.users.getFirstId();
    Long ITEM_ID = testData.items.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        Statistics stats = JPA.getEntityManagerFactory().unwrap(SessionFactory.class).getStatistics();
        // Clear all natural ID cache regions
        JPA.getEntityManagerFactory().getCache().unwrap(org.hibernate.Cache.class).evictNaturalIdRegions();
        // Clear the User entity cache region
        JPA.getEntityManagerFactory().getCache().evict(User.class);
        {
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            Session session = em.unwrap(Session.class);
            NaturalIdCacheStatistics userIdStats = stats.getNaturalIdCacheStatistics(User.class.getName() + "##NaturalId");
            assertEquals(userIdStats.getElementCountInMemory(), 0);
            User user = (User) session.byNaturalId(User.class).using("username", "johndoe").load();
            // select ID from USERS where USERNAME = ?
            // select * from USERS where ID = ?
            assertNotNull(user);
            assertEquals(userIdStats.getHitCount(), 0);
            assertEquals(userIdStats.getMissCount(), 1);
            assertEquals(userIdStats.getElementCountInMemory(), 1);
            SecondLevelCacheStatistics userStats = stats.getSecondLevelCacheStatistics(User.class.getName());
            assertEquals(userStats.getHitCount(), 0);
            assertEquals(userStats.getMissCount(), 1);
            assertEquals(userStats.getElementCountInMemory(), 1);
            tx.commit();
            em.close();
        }
        {
            // Execute the lookup again, hit the cache
            tx.begin();
            EntityManager em = JPA.createEntityManager();
            Session session = em.unwrap(Session.class);
            /* 
                   The natural identifier cache region for <code>User</code>s
                   has one element.
                 */
            NaturalIdCacheStatistics userIdStats = stats.getNaturalIdCacheStatistics(User.class.getName() + "##NaturalId");
            assertEquals(userIdStats.getElementCountInMemory(), 1);
            /* 
                   The <code>org.hibernate.Session</code> API performs natural
                   identifier lookup; this is the only API for accessing the
                   natural identifier cache.
                 */
            User user = (User) session.byNaturalId(User.class).using("username", "johndoe").load();
            assertNotNull(user);
            /* 
                   You had a cache hit for the natural identifier lookup; the
                   cache returned the identifier value of "johndoe".
                 */
            assertEquals(userIdStats.getHitCount(), 1);
            /* 
                   You also had a cache hit for the actual entity data of
                   that <code>User</code>.
                 */
            SecondLevelCacheStatistics userStats = stats.getSecondLevelCacheStatistics(User.class.getName());
            assertEquals(userStats.getHitCount(), 1);
            tx.commit();
            em.close();
        }
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) SessionFactory(org.hibernate.SessionFactory) EntityManager(javax.persistence.EntityManager) NaturalIdCacheStatistics(org.hibernate.stat.NaturalIdCacheStatistics) User(org.jpwh.model.cache.User) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) Statistics(org.hibernate.stat.Statistics) QueryStatistics(org.hibernate.stat.QueryStatistics) SecondLevelCacheStatistics(org.hibernate.stat.SecondLevelCacheStatistics) NaturalIdCacheStatistics(org.hibernate.stat.NaturalIdCacheStatistics) Cache(javax.persistence.Cache) Session(org.hibernate.Session) Test(org.testng.annotations.Test) JPATest(org.jpwh.env.JPATest)

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