Search in sources :

Example 6 with Item

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

the class Grouping method executeQueries.

@Test
public void executeQueries() throws Exception {
    storeTestData();
    CriteriaBuilder cb = JPA.getEntityManagerFactory().getCriteriaBuilder();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            // Group
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.multiselect(u.get("lastname"), cb.count(u));
            criteria.groupBy(u.get("lastname"));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 2);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                assertTrue(row[1] instanceof Long);
            }
        }
        em.clear();
        {
            // Average
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.multiselect(b.get("item").get("name"), cb.avg(b.<BigDecimal>get("amount")));
            criteria.groupBy(b.get("item").get("name"));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 2);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                assertTrue(row[1] instanceof Double);
            }
        }
        em.clear();
        {
            // Average Workaround
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            Join<Bid, Item> i = b.join("item");
            criteria.multiselect(i, cb.avg(b.<BigDecimal>get("amount")));
            criteria.groupBy(i.get("id"), i.get("name"), i.get("createdOn"), i.get("auctionEnd"), i.get("auctionType"), i.get("approved"), i.get("buyNowPrice"), i.get("seller"));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 2);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Item);
                assertTrue(row[1] instanceof Double);
            }
        }
        em.clear();
        {
            // Having
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.multiselect(u.get("lastname"), cb.count(u));
            criteria.groupBy(u.get("lastname"));
            criteria.having(cb.like(u.<String>get("lastname"), "D%"));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 1);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                assertTrue(row[1] instanceof Long);
            }
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.querying.User) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Join(javax.persistence.criteria.Join) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) List(java.util.List) Bid(org.jpwh.model.querying.Bid) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 7 with Item

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

the class Joins method executeQueries.

@Test
public void executeQueries() throws Exception {
    TestDataCategoriesItems testData = storeTestData();
    CriteriaBuilder cb = JPA.getEntityManagerFactory().getCriteriaBuilder();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            // Implicit inner join
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(cb.like(b.get("item").<String>get("name"), "Fo%"));
            Query q = em.createQuery(criteria);
            List<Bid> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Bid bid : result) {
                assertEquals(bid.getItem().getId(), testData.items.getFirstId());
            }
        }
        em.clear();
        {
            // Multiple inner
            CriteriaQuery<Bid> criteria = cb.createQuery(Bid.class);
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(cb.equal(b.get("item").get("seller").get("username"), "johndoe"));
            Query q = em.createQuery(criteria);
            List<Bid> result = q.getResultList();
            assertEquals(result.size(), 4);
        }
        em.clear();
        {
            // Multiple inner
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(cb.and(cb.equal(b.get("item").get("seller").get("username"), "johndoe"), cb.isNotNull(b.get("item").get("buyNowPrice"))));
            Query q = em.createQuery(criteria);
            List<Bid> result = q.getResultList();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            // Explicit inner
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Join<Item, Bid> b = i.join("bids");
            criteria.select(i).where(cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)));
            Query q = em.createQuery(criteria);
            List<Item> result = q.getResultList();
            assertEquals(result.size(), 1);
            assertEquals(result.get(0).getId(), testData.items.getFirstId());
        }
        em.clear();
        {
            // Explicit outer
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Join<Item, Bid> b = i.join("bids", JoinType.LEFT);
            b.on(cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)));
            criteria.multiselect(i, b);
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            assertTrue(result.get(0)[0] instanceof Item);
            assertTrue(result.get(0)[1] instanceof Bid);
            assertTrue(result.get(1)[0] instanceof Item);
            assertEquals(result.get(1)[1], null);
            assertTrue(result.get(2)[0] instanceof Item);
            assertEquals(result.get(2)[1], null);
        }
        em.clear();
        {
        // Explicit right outer
        /* TODO Right outer joins not supported in criteria, Hibernate bug JPA-2

                CriteriaQuery criteria = cb.createQuery();
                Root<Bid> b = criteria.from(Bid.class);
                Join<Bid, Item> i = b.join("item", JoinType.RIGHT);
                criteria.multiselect(b, i).where(
                   cb.or(
                      cb.isNull(b),
                      cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)))
                );

                Query q = em.createQuery(criteria);
                List<Object[]> result = q.getResultList();
                assertEquals(result.size(), 2);
                assertTrue(result.get(0)[0] instanceof Bid);
                assertTrue(result.get(0)[1] instanceof Item);
                assertEquals(result.get(1)[0], null);
                assertTrue(result.get(1)[1] instanceof Item);
                */
        }
        em.clear();
        {
            // A typical "fetch the bids collections for all items as a side effect" query
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            i.fetch("bids", JoinType.LEFT);
            criteria.select(i);
            Query q = em.createQuery(criteria);
            List<Item> result = q.getResultList();
            // 3 items, 4 bids, 5 "rows" in result!
            assertEquals(result.size(), 5);
            // In-memory "distinct"
            Set<Item> distinctResult = new LinkedHashSet<Item>(result);
            // It was only three items all along...
            assertEquals(distinctResult.size(), 3);
            boolean haveBids = false;
            for (Item item : distinctResult) {
                // No more lazy loading!
                em.detach(item);
                if (item.getBids().size() > 0) {
                    haveBids = true;
                    break;
                }
            }
            assertTrue(haveBids);
        }
        em.clear();
        {
            // Hibernate can remove the duplicate SQL resultset rows for you
            // (...who knows, some of you actually WANT the duplicates!)
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            i.fetch("bids", JoinType.LEFT);
            criteria.select(i).distinct(true);
            Query q = em.createQuery(criteria);
            List<Item> result = q.getResultList();
            // Hibernate filtered it for us in-memory
            assertEquals(result.size(), 3);
            boolean haveBids = false;
            for (Item item : result) {
                // No more lazy loading!
                em.detach(item);
                if (item.getBids().size() > 0) {
                    haveBids = true;
                    break;
                }
            }
            assertTrue(haveBids);
        }
        em.clear();
        {
            // Fetch multiple associated instances/collections
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Fetch<Item, Bid> b = i.fetch("bids", JoinType.LEFT);
            // These are non-nullable foreign key columns, inner join or
            b.fetch("bidder");
            // outer doesn't make a difference!
            i.fetch("seller", JoinType.LEFT);
            criteria.select(i).distinct(true);
            Query q = em.createQuery(criteria);
            List<Item> result = q.getResultList();
            assertEquals(result.size(), 2);
            boolean haveBids = false;
            boolean haveBidder = false;
            boolean haveSeller = false;
            for (Item item : result) {
                // No more lazy loading!
                em.detach(item);
                if (item.getBids().size() > 0) {
                    haveBids = true;
                    Bid bid = item.getBids().iterator().next();
                    if (bid.getBidder() != null && bid.getBidder().getUsername() != null) {
                        haveBidder = true;
                    }
                }
                if (item.getSeller() != null && item.getSeller().getUsername() != null)
                    haveSeller = true;
            }
            assertTrue(haveBids);
            assertTrue(haveBidder);
            assertTrue(haveSeller);
        }
        em.clear();
        {
            // SQL Cartesian product of multiple collections! Bad!
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            i.fetch("bids", JoinType.LEFT);
            // Cartesian product, bad!
            i.fetch("images", JoinType.LEFT);
            criteria.select(i).distinct(true);
            Query q = em.createQuery(criteria);
            List<Item> result = q.getResultList();
            assertEquals(result.size(), 3);
            boolean haveBids = false;
            boolean haveImages = false;
            for (Item item : result) {
                // No more lazy loading!
                em.detach(item);
                if (item.getBids().size() > 0)
                    haveBids = true;
                if (item.getImages().size() > 0)
                    haveImages = true;
            }
            assertTrue(haveBids);
            assertTrue(haveImages);
        }
        em.clear();
        {
            // Theta style inner join
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            Root<LogRecord> log = criteria.from(LogRecord.class);
            criteria.where(cb.equal(u.get("username"), log.get("username")));
            criteria.multiselect(u, log);
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            for (Object[] row : result) {
                assertTrue(row[0] instanceof User);
                assertTrue(row[1] instanceof LogRecord);
            }
            assertEquals(result.size(), 2);
        }
        em.clear();
        {
            // Theta style inner join, multiple
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Root<Bid> b = criteria.from(Bid.class);
            criteria.where(cb.equal(b.get("item"), i), cb.equal(i.get("seller"), b.get("bidder")));
            criteria.multiselect(i, b);
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 0);
        }
        em.clear();
        {
            // Inner join with implicit ID comparison
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Root<User> u = criteria.from(User.class);
            criteria.where(cb.equal(i.get("seller"), u), cb.like(u.<String>get("username"), "j%"));
            criteria.multiselect(i, u);
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Item);
                assertTrue(row[1] instanceof User);
            }
        }
        em.clear();
        {
            // Inner join with explicit ID comparison
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Root<User> u = criteria.from(User.class);
            criteria.where(cb.equal(i.get("seller").get("id"), u.get("id")), cb.like(u.<String>get("username"), "j%"));
            criteria.multiselect(i, u);
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Item);
                assertTrue(row[1] instanceof User);
            }
        }
        em.clear();
        {
            // Binding an entity parameter
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.where(cb.equal(i.get("seller"), cb.parameter(User.class, "seller")));
            criteria.select(i);
            Query q = em.createQuery(criteria);
            User someUser = em.find(User.class, testData.users.getFirstId());
            q.setParameter("seller", someUser);
            List<Item> result = q.getResultList();
            assertEquals(result.size(), 2);
        }
        em.clear();
        {
            // Binding ID parameter
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.where(cb.equal(i.get("seller").get("id"), cb.parameter(Long.class, "sellerId")));
            criteria.select(i);
            Query q = em.createQuery(criteria);
            Long USER_ID = testData.users.getFirstId();
            q.setParameter("sellerId", USER_ID);
            List<Item> result = q.getResultList();
            assertEquals(result.size(), 2);
        }
        em.clear();
        {
            // Not a join, just ID comparison
            CriteriaQuery<Bid> criteria = cb.createQuery(Bid.class);
            Root<Bid> b = criteria.from(Bid.class);
            criteria.where(cb.equal(b.get("item").get("id"), cb.parameter(Long.class, "itemId")));
            criteria.select(b);
            Query q = em.createQuery(criteria);
            q.setParameter("itemId", testData.items.getFirstId());
            List<Bid> result = q.getResultList();
            assertEquals(result.size(), 3);
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserTransaction(javax.transaction.UserTransaction) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) User(org.jpwh.model.querying.User) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Query(javax.persistence.Query) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Join(javax.persistence.criteria.Join) BigDecimal(java.math.BigDecimal) Fetch(javax.persistence.criteria.Fetch) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) LogRecord(org.jpwh.model.querying.LogRecord) List(java.util.List) Bid(org.jpwh.model.querying.Bid) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 8 with Item

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

the class CallStoredProcedures method callReturningRefCursor.

@Test(groups = "POSTGRESQL")
public void callReturningRefCursor() throws Exception {
    storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        /*
            em.unwrap(Session.class).doWork(
                new CallProcedureAndPrintResult() {
                    @Override
                    protected CallableStatement prepare(Connection connection) throws SQLException {
                        CallableStatement statement = connection.prepareCall("{? = call FIND_ITEMS()}");
                        statement.registerOutParameter(1, Types.OTHER);
                        return statement;
                    }

                    @Override
                    protected ResultSet execute(CallableStatement statement) throws SQLException {
                        statement.execute();
                        return (ResultSet)statement.getObject(1);
                    }
                }
            );
            */
        StoredProcedureQuery query = em.createStoredProcedureQuery("FIND_ITEMS", Item.class);
        query.registerStoredProcedureParameter(1, void.class, ParameterMode.REF_CURSOR);
        List<Item> result = query.getResultList();
        for (Item item : result) {
        // ...
        }
        assertEquals(result.size(), 3);
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) StoredProcedureQuery(javax.persistence.StoredProcedureQuery) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 9 with Item

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

the class CallStoredProcedures method callReturningMultipleResultsNative.

@Test(groups = "MYSQL")
public void callReturningMultipleResultsNative() throws Exception {
    storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            Session session = em.unwrap(Session.class);
            org.hibernate.procedure.ProcedureCall call = session.createStoredProcedureCall("APPROVE_ITEMS", Item.class);
            org.hibernate.procedure.ProcedureOutputs callOutputs = call.getOutputs();
            boolean[] expectedResults = new boolean[3];
            int i = 0;
            org.hibernate.result.Output output;
            /* 
                   As long as <code>getCurrent()</code> doesn't return <code>null</code>, there
                   are more outputs to process.
                 */
            while ((output = callOutputs.getCurrent()) != null) {
                /* 
                       An output might be a result set, test and cast it.
                     */
                if (output.isResultSet()) {
                    List<Item> result = ((org.hibernate.result.ResultSetOutput) output).getResultList();
                    // one row, the second with two rows
                    if (i == 0) {
                        assertEquals(result.size(), 1);
                    } else if (i == 1) {
                        assertEquals(result.size(), 2);
                    }
                    expectedResults[i] = true;
                } else {
                    /* 
                           If an output is not a result set, it's an update count.
                         */
                    int updateCount = ((org.hibernate.result.UpdateCountOutput) output).getUpdateCount();
                    // ...
                    // We also updated one row in the procedure
                    assertEquals(updateCount, 1);
                    expectedResults[i] = true;
                }
                /* 
                       Proceed with the next output, if there is any.
                     */
                if (!callOutputs.goToNext())
                    break;
                i++;
            }
            for (boolean expectedResult : expectedResults) {
                assertTrue(expectedResult);
            }
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) List(java.util.List) Session(org.hibernate.Session) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 10 with Item

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

the class CallStoredProcedures method callWithInOutParameters.

@Test(groups = "MYSQL")
public void callWithInOutParameters() throws Exception {
    TestDataCategoriesItems testDataCategoriesItems = storeTestData();
    final Long ITEM_ID = testDataCategoriesItems.items.getFirstId();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        /*
            em.unwrap(Session.class).doWork(
                new CallProcedureAndPrintResult() {
                    @Override
                    protected CallableStatement prepare(Connection connection) throws SQLException {
                        CallableStatement statement = connection.prepareCall("{call FIND_ITEM_TOTAL(?, ?)}");
                        statement.setLong(1, ITEM_ID);
                        statement.registerOutParameter(2, Types.VARCHAR);
                        return statement;
                    }

                    @Override
                    protected ResultSet execute(CallableStatement statement) throws SQLException {
                        statement.execute();
                        System.out.println("### TOTAL NR. OF ITEMS: " + statement.getLong(2));
                        return statement.getResultSet();
                    }
                }
            );
            */
        StoredProcedureQuery query = em.createStoredProcedureQuery("FIND_ITEM_TOTAL", Item.class);
        /* 
               Register all parameters by position (starting at 1) and their type.
             */
        query.registerStoredProcedureParameter(1, Long.class, ParameterMode.IN);
        query.registerStoredProcedureParameter(2, Long.class, ParameterMode.OUT);
        /* 
               Bind values to the input parameters.
             */
        query.setParameter(1, ITEM_ID);
        /* 
               Retrieve the result set returned by the procedure.
             */
        List<Item> result = query.getResultList();
        for (Item item : result) {
            // ...
            assertEquals(item.getId(), ITEM_ID);
        }
        /* 
               After you've retrieved the result sets, you can access the output parameter values.
             */
        Long totalNumberOfItems = (Long) query.getOutputParameterValue(2);
        assertEquals(result.size(), 1);
        assertEquals(totalNumberOfItems, new Long(3));
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) StoredProcedureQuery(javax.persistence.StoredProcedureQuery) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Aggregations

EntityManager (javax.persistence.EntityManager)35 UserTransaction (javax.transaction.UserTransaction)35 Item (org.jpwh.model.querying.Item)35 Test (org.testng.annotations.Test)34 QueryingTest (org.jpwh.test.querying.QueryingTest)27 List (java.util.List)22 Query (javax.persistence.Query)20 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)16 TypedQuery (javax.persistence.TypedQuery)13 User (org.jpwh.model.querying.User)13 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)12 Session (org.hibernate.Session)12 Root (javax.persistence.criteria.Root)11 Bid (org.jpwh.model.querying.Bid)11 BigDecimal (java.math.BigDecimal)10 Date (java.util.Date)5 Set (java.util.Set)5 StoredProcedureQuery (javax.persistence.StoredProcedureQuery)4 Address (org.jpwh.model.querying.Address)4 LinkedHashSet (java.util.LinkedHashSet)3