Search in sources :

Example 1 with Address

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

the class QueryingTest method storeTestData.

public TestDataCategoriesItems storeTestData() throws Exception {
    UserTransaction tx = TM.getUserTransaction();
    tx.begin();
    EntityManager em = JPA.createEntityManager();
    Long[] categoryIds = new Long[4];
    Long[] itemIds = new Long[3];
    Long[] userIds = new Long[3];
    User johndoe = new User("johndoe", "John", "Doe");
    Address homeAddress = new Address("Some Street 123", "12345", "Some City");
    johndoe.setActivated(true);
    johndoe.setHomeAddress(homeAddress);
    em.persist(johndoe);
    userIds[0] = johndoe.getId();
    User janeroe = new User("janeroe", "Jane", "Roe");
    janeroe.setActivated(true);
    janeroe.setHomeAddress(new Address("Other Street 11", "1234", "Other City"));
    em.persist(janeroe);
    userIds[1] = janeroe.getId();
    User robertdoe = new User("robertdoe", "Robert", "Doe");
    em.persist(robertdoe);
    userIds[2] = robertdoe.getId();
    Category categoryOne = new Category("One");
    em.persist(categoryOne);
    categoryIds[0] = categoryOne.getId();
    Item item = new Item("Foo", CalendarUtil.TOMORROW.getTime(), johndoe);
    item.setBuyNowPrice(new BigDecimal("19.99"));
    em.persist(item);
    itemIds[0] = item.getId();
    categoryOne.getItems().add(item);
    item.getCategories().add(categoryOne);
    for (int i = 1; i <= 3; i++) {
        Bid bid = new Bid(item, robertdoe, new BigDecimal(98 + i));
        item.getBids().add(bid);
        em.persist(bid);
    }
    item.getImages().add(new Image("Foo", "foo.jpg", 640, 480));
    item.getImages().add(new Image("Bar", "bar.jpg", 800, 600));
    item.getImages().add(new Image("Baz", "baz.jpg", 1024, 768));
    Category categoryTwo = new Category("Two");
    categoryTwo.setParent(categoryOne);
    em.persist(categoryTwo);
    categoryIds[1] = categoryTwo.getId();
    item = new Item("Bar", CalendarUtil.TOMORROW.getTime(), johndoe);
    em.persist(item);
    itemIds[1] = item.getId();
    categoryTwo.getItems().add(item);
    item.getCategories().add(categoryTwo);
    Bid bid = new Bid(item, janeroe, new BigDecimal("4.99"));
    item.getBids().add(bid);
    em.persist(bid);
    item = new Item("Baz", CalendarUtil.AFTER_TOMORROW.getTime(), janeroe);
    item.setApproved(false);
    em.persist(item);
    itemIds[2] = item.getId();
    categoryTwo.getItems().add(item);
    item.getCategories().add(categoryTwo);
    Category categoryThree = new Category("Three");
    categoryThree.setParent(categoryOne);
    em.persist(categoryThree);
    categoryIds[2] = categoryThree.getId();
    Category categoryFour = new Category("Four");
    categoryFour.setParent(categoryTwo);
    em.persist(categoryFour);
    categoryIds[3] = categoryFour.getId();
    CreditCard cc = new CreditCard("John Doe", "1234123412341234", "06", "2015");
    em.persist(cc);
    BankAccount ba = new BankAccount("Jane Roe", "445566", "One Percent Bank Inc.", "999");
    em.persist(ba);
    LogRecord lr = new LogRecord("johndoe", "This is a log message");
    em.persist(lr);
    lr = new LogRecord("johndoe", "Another log message");
    em.persist(lr);
    tx.commit();
    em.close();
    TestDataCategoriesItems testData = new TestDataCategoriesItems();
    testData.categories = new TestData(categoryIds);
    testData.items = new TestData(itemIds);
    testData.users = new TestData(userIds);
    return testData;
}
Also used : UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.querying.User) Category(org.jpwh.model.querying.Category) Address(org.jpwh.model.querying.Address) TestData(org.jpwh.shared.util.TestData) BankAccount(org.jpwh.model.inheritance.tableperclass.BankAccount) Image(org.jpwh.model.querying.Image) BigDecimal(java.math.BigDecimal) CreditCard(org.jpwh.model.inheritance.tableperclass.CreditCard) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) LogRecord(org.jpwh.model.querying.LogRecord) Bid(org.jpwh.model.querying.Bid)

Example 2 with Address

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

the class HibernateCriteria method executeQueries.

@Test
public void executeQueries() throws Exception {
    TestDataCategoriesItems testData = storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        Session session = em.unwrap(Session.class);
        {
            // Selection
            org.hibernate.Criteria criteria = session.createCriteria(Item.class);
            List<Item> items = criteria.list();
            assertEquals(items.size(), 3);
        }
        em.clear();
        {
            DetachedCriteria criteria = DetachedCriteria.forClass(Item.class);
            List<Item> items = criteria.getExecutableCriteria(session).list();
            assertEquals(items.size(), 3);
        }
        em.clear();
        {
            // Ordering
            List<User> users = session.createCriteria(User.class).addOrder(Order.asc("firstname")).addOrder(Order.asc("lastname")).list();
            assertEquals(users.size(), 3);
            assertEquals(users.get(0).getFirstname(), "Jane");
            assertEquals(users.get(1).getFirstname(), "John");
            assertEquals(users.get(2).getFirstname(), "Robert");
        }
        em.clear();
        {
            // Restriction
            List<Item> items = session.createCriteria(Item.class).add(Restrictions.eq("name", "Foo")).list();
            assertEquals(items.size(), 1);
        }
        em.clear();
        {
            List<User> users = session.createCriteria(User.class).add(Restrictions.like("username", "j", MatchMode.START).ignoreCase()).list();
            assertEquals(users.size(), 2);
        }
        em.clear();
        {
            List<User> users = session.createCriteria(User.class).add(Restrictions.eq("homeAddress.city", "Some City")).list();
            assertEquals(users.size(), 1);
            assertEquals(users.get(0).getUsername(), "johndoe");
        }
        em.clear();
        {
            List<User> users = session.createCriteria(User.class).add(Restrictions.sqlRestriction("length({alias}.USERNAME) < ?", 8, StandardBasicTypes.INTEGER)).list();
            assertEquals(users.size(), 2);
        }
        em.clear();
        {
            // Projection
            List<Object[]> result = session.createCriteria(User.class).setProjection(Projections.projectionList().add(Projections.property("id")).add(Projections.property("username")).add(Projections.property("homeAddress"))).list();
            assertEquals(result.size(), 3);
            for (Object[] tuple : result) {
                assertTrue(tuple[0] instanceof Long);
                assertTrue(tuple[1] instanceof String);
                assertTrue(tuple[2] == null || tuple[2] instanceof Address);
            }
        }
        em.clear();
        {
            List<String> result = session.createCriteria(Item.class).setProjection(Projections.projectionList().add(Projections.sqlProjection("NAME || ':' || AUCTIONEND as RESULT", new String[] { "RESULT" }, new Type[] { StandardBasicTypes.STRING }))).list();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            List<Object[]> result = session.createCriteria(User.class).setProjection(Projections.projectionList().add(Projections.groupProperty("lastname")).add(Projections.rowCount())).list();
            assertEquals(result.size(), 2);
            for (Object[] tuple : result) {
                assertTrue(tuple[0] instanceof String);
                assertTrue(tuple[1] instanceof Long);
            }
        }
        em.clear();
        {
            List<Object[]> result = session.createCriteria(Bid.class).setProjection(Projections.projectionList().add(Projections.groupProperty("item")).add(Projections.avg("amount"))).list();
            assertEquals(result.size(), 2);
            for (Object[] tuple : result) {
                assertTrue(tuple[0] instanceof Item);
                assertTrue(tuple[1] instanceof Double);
            }
        }
        em.clear();
        {
            // Joins
            List<Bid> result = session.createCriteria(Bid.class).createCriteria(// Inner join
            "item").add(Restrictions.like("name", "Fo", MatchMode.START)).list();
            assertEquals(result.size(), 3);
            for (Bid bid : result) {
                assertEquals(bid.getItem().getId(), testData.items.getFirstId());
            }
        }
        em.clear();
        {
            List<Bid> result = session.createCriteria(Bid.class).createCriteria(// Inner join
            "item").add(Restrictions.isNotNull("buyNowPrice")).createCriteria(// Inner join
            "seller").add(Restrictions.eq("username", "johndoe")).list();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            List<Object[]> result = session.createCriteria(Bid.class, "b").createAlias("item", "i", JoinType.RIGHT_OUTER_JOIN).add(Restrictions.or(Restrictions.isNull("b.id"), Restrictions.gt("amount", new BigDecimal(100)))).setResultTransformer(Criteria.PROJECTION).list();
            assertEquals(result.size(), 2);
            // Criteria quirk: the root entity alias is always last in the result tuple
            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);
        }
        em.clear();
        {
            List<Bid> result = session.createCriteria(Bid.class).createCriteria(// Inner join
            "item").createAlias("seller", // Inner join
            "s").add(Restrictions.and(Restrictions.eq("s.username", "johndoe"), Restrictions.isNotNull("buyNowPrice"))).list();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            // Fetching
            List<Item> result = session.createCriteria(Item.class).setFetchMode("bids", FetchMode.JOIN).list();
            // 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 : result) {
                // No more lazy loading!
                em.detach(item);
                if (item.getBids().size() > 0) {
                    haveBids = true;
                    break;
                }
            }
            assertTrue(haveBids);
        }
        em.clear();
        {
            List<Item> result = session.createCriteria(Item.class).setFetchMode("bids", FetchMode.JOIN).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
            // 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();
        {
            List<Item> result = session.createCriteria(Item.class).createAlias("bids", "b", JoinType.LEFT_OUTER_JOIN).setFetchMode("b", FetchMode.JOIN).createAlias("b.bidder", "bdr", JoinType.INNER_JOIN).setFetchMode("bdr", FetchMode.JOIN).createAlias("seller", "s", JoinType.LEFT_OUTER_JOIN).setFetchMode("s", FetchMode.JOIN).list();
            result = new ArrayList<Item>(new LinkedHashSet<Item>(result));
            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();
        {
            // Subquery
            DetachedCriteria sq = DetachedCriteria.forClass(Item.class, "i");
            sq.add(Restrictions.eqProperty("i.seller.id", "u.id"));
            sq.setProjection(Projections.rowCount());
            List<User> result = session.createCriteria(User.class, "u").add(Subqueries.lt(1l, sq)).list();
            assertEquals(result.size(), 1);
            User user = result.iterator().next();
            assertEquals(user.getId(), testData.users.getFirstId());
        }
        em.clear();
        {
            DetachedCriteria sq = DetachedCriteria.forClass(Bid.class, "b");
            sq.add(Restrictions.eqProperty("b.item.id", "i.id"));
            sq.setProjection(Projections.property("amount"));
            List<Item> result = session.createCriteria(Item.class, "i").add(Subqueries.geAll(new BigDecimal(10), sq)).list();
            assertEquals(result.size(), 2);
        }
        em.clear();
        {
            // Query by example: Find all users with last name "Doe"
            /* 
                   First, create an "empty" instance of <code>User</code> as a template for your
                   search and set the property values you are looking for. You want to retrieve
                   people with the last name "Doe".
                 */
            User template = new User();
            template.setLastname("Doe");
            /* 
                   Create an instance of <code>Example</code> with the template, this API allows
                   you to fine-tune the search. You want the case of the last name to be ignored,
                   and a substring search, so "Doe", "DoeX", or "Doe Y" would match. In addition, the
                   <code>User</code> class has a <code>boolean</code> property called
                   <code>activated</code>. As a primitive, it can't be <code>null</code> and its
                   default value is <code>false</code>, so Hibernate would include it in the search
                   and only return users that aren't activated. As you want all users, you tell
                   Hibernate to ignore that property when building the search query.
                 */
            org.hibernate.criterion.Example example = Example.create(template);
            example.ignoreCase();
            example.enableLike(MatchMode.START);
            example.excludeProperty("activated");
            /* 
                   The <code>Example</code> is added to a <code>Criteria</code> as a restriction.
                 */
            List<User> users = session.createCriteria(User.class).add(example).list();
            assertEquals(users.size(), 2);
        }
        em.clear();
        {
            // Find all items which have a name starting with "B" or "b", and a
            // seller with the last name "Doe"
            Item itemTemplate = new Item();
            itemTemplate.setName("B");
            Example exampleItem = Example.create(itemTemplate);
            exampleItem.ignoreCase();
            exampleItem.enableLike(MatchMode.START);
            exampleItem.excludeProperty("auctionType");
            exampleItem.excludeProperty("createdOn");
            User userTemplate = new User();
            userTemplate.setLastname("Doe");
            Example exampleUser = Example.create(userTemplate);
            exampleUser.excludeProperty("activated");
            List<Item> items = session.createCriteria(Item.class).add(exampleItem).createCriteria("seller").add(exampleUser).list();
            assertEquals(items.size(), 1);
            assertTrue(items.get(0).getName().startsWith("B"));
            assertEquals(items.get(0).getSeller().getLastname(), "Doe");
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.querying.User) LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) Address(org.jpwh.model.querying.Address) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) ArrayList(java.util.ArrayList) Criteria(org.hibernate.Criteria) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) BigDecimal(java.math.BigDecimal) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) Example(org.hibernate.criterion.Example) ArrayList(java.util.ArrayList) List(java.util.List) Bid(org.jpwh.model.querying.Bid) Session(org.hibernate.Session) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 3 with Address

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

the class Projection method executeQueries.

@Test
public void executeQueries() throws Exception {
    TestDataCategoriesItems testData = storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            Query query = em.createNamedQuery("product");
            List<Object[]> result = query.getResultList();
            Set<Item> items = new HashSet();
            Set<Bid> bids = new HashSet();
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Item);
                items.add((Item) row[0]);
                assertTrue(row[1] instanceof Bid);
                bids.add((Bid) row[1]);
            }
            assertEquals(items.size(), 3);
            assertEquals(bids.size(), 4);
            // Cartesian product!
            assertEquals(result.size(), 12);
        }
        em.clear();
        {
            Query q = em.createNamedQuery("scalarProduct");
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            Set<Long> ids = new HashSet();
            Set<String> names = new HashSet();
            Set<BigDecimal> prices = new HashSet();
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Long);
                ids.add((Long) row[0]);
                assertTrue(row[1] instanceof String);
                names.add((String) row[1]);
                assertTrue(row[2] == null || row[2] instanceof BigDecimal);
                prices.add((BigDecimal) row[2]);
            }
            assertEquals(ids.size(), 3, "ids");
            assertEquals(names.size(), 3, "names");
            assertEquals(prices.size(), 2, "prices");
        }
        em.clear();
        {
            Query q = em.createNamedQuery("transient");
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            Object[] firstRow = result.get(0);
            assertTrue(firstRow[0] instanceof Long);
            assertTrue(firstRow[1] instanceof String);
            assertTrue(firstRow[2] instanceof Address);
        }
        em.clear();
        {
            Query q = em.createNamedQuery("distinct");
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            Query q = em.createNamedQuery("dynamicInstance");
            List<ItemSummary> result = q.getResultList();
            assertEquals(result.size(), 3);
        }
        // All following are more function call examples, with variations
        em.clear();
        {
            Query q = em.createNamedQuery("concat");
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            Query q = em.createNamedQuery("coalesce");
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                // Never NULL!
                assertTrue(row[1] instanceof BigDecimal);
            }
        }
        em.clear();
        {
            Query q = em.createNamedQuery("caseWhen");
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                assertTrue(row[1] instanceof String);
            }
        }
        em.clear();
        {
            Query query = em.createNamedQuery("count");
            Long count = (Long) query.getSingleResult();
            assertEquals(count, new Long(3));
        }
        em.clear();
        {
            Query q = em.createNamedQuery("countDistinct");
            Long count = (Long) q.getSingleResult();
            assertEquals(count, new Long(3));
        }
        em.clear();
        {
            Query q = em.createNamedQuery("sum");
            BigDecimal sum = (BigDecimal) q.getSingleResult();
            assertEquals(sum.toString(), "304.99");
        }
        em.clear();
        {
            Query q = em.createNamedQuery("minMax");
            q.setParameter("itemId", testData.items.getFirstId());
            Object[] result = (Object[]) q.getSingleResult();
            assertEquals(((BigDecimal) result[0]).compareTo(new BigDecimal("99")), 0);
            assertEquals(((BigDecimal) result[1]).compareTo(new BigDecimal("101")), 0);
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) Set(java.util.Set) HashSet(java.util.HashSet) Query(javax.persistence.Query) Address(org.jpwh.model.querying.Address) BigDecimal(java.math.BigDecimal) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) List(java.util.List) Bid(org.jpwh.model.querying.Bid) HashSet(java.util.HashSet) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 4 with Address

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

the class Projection 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();
        {
            // Product
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(cb.tuple(i, b));
            /* Convenient alternative:
                criteria.multiselect(
                    criteria.from(Item.class),
                    criteria.from(Bid.class)
                );
                */
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            // Cartesian product!
            assertEquals(result.size(), 12);
            Set<Item> items = new HashSet();
            Set<Bid> bids = new HashSet();
            for (Object[] row : result) {
                assertTrue(row[0] instanceof Item);
                items.add((Item) row[0]);
                assertTrue(row[1] instanceof Bid);
                bids.add((Bid) row[1]);
            }
            assertEquals(items.size(), 3);
            assertEquals(bids.size(), 4);
        }
        em.clear();
        {
            // Transient result
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            // Returns List of Object[]
            criteria.multiselect(u.get("id"), u.get("username"), u.get("homeAddress"));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            Object[] firstRow = result.get(0);
            assertTrue(firstRow[0] instanceof Long);
            assertTrue(firstRow[1] instanceof String);
            assertTrue(firstRow[2] instanceof Address);
        }
        em.clear();
        {
            // Distinct
            CriteriaQuery<String> criteria = cb.createQuery(String.class);
            criteria.select(criteria.from(Item.class).<String>get("name"));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Distinct
            CriteriaQuery<String> criteria = cb.createQuery(String.class);
            criteria.select(criteria.from(Item.class).<String>get("name"));
            criteria.distinct(true);
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Dynamic instance creation
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(cb.construct(// Must have the right constructor!
            ItemSummary.class, i.get("id"), i.get("name"), i.get("auctionEnd")));
            Query q = em.createQuery(criteria);
            List<ItemSummary> result = q.getResultList();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            // Tuple API
            CriteriaQuery<Tuple> criteria = cb.createTupleQuery();
            // Or: CriteriaQuery<Tuple> criteria = cb.createQuery(Tuple.class);
            criteria.multiselect(// Aliases optional!
            criteria.from(Item.class).alias("i"), criteria.from(Bid.class).alias("b"));
            TypedQuery<Tuple> query = em.createQuery(criteria);
            List<Tuple> result = query.getResultList();
            Set<Item> items = new HashSet();
            Set<Bid> bids = new HashSet();
            for (Tuple tuple : result) {
                // Indexed
                Item item = tuple.get(0, Item.class);
                Bid bid = tuple.get(1, Bid.class);
                // Alias
                item = tuple.get("i", Item.class);
                bid = tuple.get("b", Bid.class);
                // Meta
                for (TupleElement<?> element : tuple.getElements()) {
                    Class clazz = element.getJavaType();
                    String alias = element.getAlias();
                    Object value = tuple.get(element);
                }
                items.add(item);
                bids.add(bid);
            }
            // Cartesian product!
            assertEquals(result.size(), 12);
            assertEquals(items.size(), 3);
            assertEquals(bids.size(), 4);
        }
        em.clear();
        // All following are more function call examples, with variations
        {
            // Concat
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(cb.concat(cb.concat(i.<String>get("name"), ":"), // Note the cast of Date!
            i.<String>get("auctionEnd")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Coalesce
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.multiselect(i.get("name"), cb.coalesce(i.<BigDecimal>get("buyNowPrice"), 0));
            Query q = em.createQuery(criteria);
            List<Object[]> result = q.getResultList();
            assertEquals(result.size(), 3);
            for (Object[] row : result) {
                assertTrue(row[0] instanceof String);
                // Never NULL!
                assertTrue(row[1] instanceof BigDecimal);
            }
        }
        em.clear();
        {
        // Case When
        /*
                CriteriaQuery criteria = cb.createQuery();
                TODO String literals not supported, Hibernate bug HHH-8124
                Root<User> u = criteria.from(User.class);
                criteria.multiselect(
                    u.get("username"),
                    cb.selectCase()
                        .when(
                            cb.equal(
                                cb.length(u.get("homeAddress").<String>get("zipcode")), 5
                            ), "Germany"
                        )
                        .when(
                            cb.equal(
                                cb.length(u.get("homeAddress").<String>get("zipcode")), 4
                            ), "Switzerland"
                        )
                        .otherwise("Other")
                );

                Query q = em.createQuery(criteria);
                List<Object[]> result = q.getResultList();
                assertEquals(result.size(), 3);
                for (Object[] row : result) {
                    assertTrue(row[0] instanceof String);
                    assertTrue(row[1] instanceof String);
                }
                */
        }
        em.clear();
        {
            // Count
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(cb.count(criteria.from(Item.class)));
            Query q = em.createQuery(criteria);
            Long count = (Long) q.getSingleResult();
            assertEquals(count, new Long(3));
        }
        em.clear();
        {
            // count(distinct ...)
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(cb.countDistinct(criteria.from(Item.class).get("name")));
            Query q = em.createQuery(criteria);
            Long count = (Long) q.getSingleResult();
            assertEquals(count, new Long(3));
        }
        em.clear();
        {
            // Sum
            CriteriaQuery<Number> criteria = cb.createQuery(Number.class);
            criteria.select(cb.sum(criteria.from(Bid.class).<BigDecimal>get("amount")));
            Query q = em.createQuery(criteria);
            BigDecimal sum = (BigDecimal) q.getSingleResult();
            assertEquals(sum.compareTo(new BigDecimal("304.99")), 0);
        }
        em.clear();
        {
            // Min/Max
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.multiselect(cb.min(b.<BigDecimal>get("amount")), cb.max(b.<BigDecimal>get("amount")));
            criteria.where(cb.equal(b.get("item").<Long>get("id"), cb.parameter(Long.class, "itemId")));
            Query q = em.createQuery(criteria);
            q.setParameter("itemId", testData.items.getFirstId());
            Object[] result = (Object[]) q.getSingleResult();
            assertEquals(((BigDecimal) result[0]).compareTo(new BigDecimal("99")), 0);
            assertEquals(((BigDecimal) result[1]).compareTo(new BigDecimal("101")), 0);
        }
        em.clear();
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserTransaction(javax.transaction.UserTransaction) Set(java.util.Set) HashSet(java.util.HashSet) User(org.jpwh.model.querying.User) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) Address(org.jpwh.model.querying.Address) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) BigDecimal(java.math.BigDecimal) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) TupleElement(javax.persistence.TupleElement) List(java.util.List) Bid(org.jpwh.model.querying.Bid) Tuple(javax.persistence.Tuple) HashSet(java.util.HashSet) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Aggregations

BigDecimal (java.math.BigDecimal)4 EntityManager (javax.persistence.EntityManager)4 UserTransaction (javax.transaction.UserTransaction)4 Address (org.jpwh.model.querying.Address)4 Bid (org.jpwh.model.querying.Bid)4 Item (org.jpwh.model.querying.Item)4 List (java.util.List)3 Set (java.util.Set)3 User (org.jpwh.model.querying.User)3 QueryingTest (org.jpwh.test.querying.QueryingTest)3 Test (org.testng.annotations.Test)3 HashSet (java.util.HashSet)2 Query (javax.persistence.Query)2 ArrayList (java.util.ArrayList)1 LinkedHashSet (java.util.LinkedHashSet)1 Tuple (javax.persistence.Tuple)1 TupleElement (javax.persistence.TupleElement)1 TypedQuery (javax.persistence.TypedQuery)1 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)1 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)1