@Override public Set<String> getTagsSuggest(String url) { String hashUrl = MD5Util.md5Hex(url); CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> query = cb.createTupleQuery(); Root<Bookmark> root = query.from(Bookmark.class); // joins SetJoin<Bookmark, String> tagsJoin = root.joinSet("tags"); query.select(cb.tuple(tagsJoin.alias("tag"), cb.count(tagsJoin).alias("count_tags"))); query.where(cb.equal(root.get("hashUrl"), hashUrl)); query.groupBy(tagsJoin); query.orderBy(cb.desc(cb.count(tagsJoin))); // top five tags List<Tuple> result = entityManager.createQuery(query).setMaxResults(5).getResultList(); Set<String> topTags = new HashSet<String>(); for (Tuple t : result) { topTags.add((String) t.get("tag")); } return topTags; }
@Override public Map<String, Long> countTagsByUser(String userName) { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Tuple> query = cb.createTupleQuery(); Root<Bookmark> root = query.from(Bookmark.class); // joins SetJoin<Bookmark, String> tagsJoin = root.joinSet("tags"); Join<Bookmark, User> userJoin = root.join("user"); query.select(cb.tuple(tagsJoin.alias("tag"), cb.count(tagsJoin).alias("count_tags"))); query.where(cb.equal(userJoin.get("userName"), userName)); query.groupBy(tagsJoin); query.orderBy(cb.desc(cb.count(tagsJoin))); List<Tuple> result = entityManager.createQuery(query).setMaxResults(30).getResultList(); Map<String, Long> tagRanking = new TreeMap<String, Long>(); for (Tuple t : result) { tagRanking.put((String) t.get("tag"), (Long) t.get("count_tags")); } return tagRanking; }
@Test public void testInvalidTupleIndexAccess() { EntityManager em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); Customer c1 = new Customer(); c1.setId("c1"); c1.setAge(18); c1.setName("Bob"); em.persist(c1); em.getTransaction().commit(); em.close(); // the actual assertion block em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); Root<Customer> customerRoot = criteria.from(Customer.class); criteria.multiselect(customerRoot.get(Customer_.name), customerRoot.get(Customer_.age)); List<Tuple> results = em.createQuery(criteria).getResultList(); assertEquals(1, results.size()); Tuple tuple = results.get(0); try { tuple.get(99); fail("99 is invalid index"); } catch (IllegalArgumentException expected) { } try { tuple.get(99, String.class); fail("99 is invalid index"); } catch (IllegalArgumentException expected) { } tuple.get(0, String.class); tuple.get(1, Integer.class); try { tuple.get(0, java.util.Date.class); fail("Date is invalid type"); } catch (IllegalArgumentException expected) { } em.getTransaction().commit(); em.close(); em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); em.createQuery("delete Customer").executeUpdate(); em.getTransaction().commit(); em.close(); }
@Test public void testVariousTupleAccessMethods() { EntityManager em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); Customer c1 = new Customer(); c1.setId("c1"); c1.setAge(18); c1.setName("Bob"); em.persist(c1); em.getTransaction().commit(); em.close(); em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); Root<Customer> customerRoot = criteria.from(Customer.class); Path<String> namePath = customerRoot.get(Customer_.name); namePath.alias("NAME"); Path<Integer> agePath = customerRoot.get(Customer_.age); agePath.alias("AGE"); criteria.multiselect(namePath, agePath); List<Tuple> results = em.createQuery(criteria).getResultList(); Tuple tuple = results.get(0); assertNotNull(tuple); assertNotNull(tuple.get("NAME")); assertNotNull(tuple.get("NAME", String.class)); try { tuple.get("NAME", Date.class); fail("Accessing Customer#name tuple as Date should have thrown exception"); } catch (IllegalArgumentException expected) { } em.getTransaction().commit(); em.close(); em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); em.createQuery("delete Customer").executeUpdate(); em.getTransaction().commit(); em.close(); }
@Test public void testTuple() { EntityManager em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); Customer c1 = new Customer(); c1.setId("c1"); c1.setAge(18); c1.setName("Bob"); em.persist(c1); em.getTransaction().commit(); em.close(); em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); Root<Customer> customerRoot = criteria.from(Customer.class); Path<String> namePath = customerRoot.get(Customer_.name); Path<Integer> agePath = customerRoot.get(Customer_.age); agePath.alias("age"); criteria.multiselect(namePath, agePath); List<Tuple> results = em.createQuery(criteria).getResultList(); assertEquals(1, results.size()); Object resultElement = results.get(0); assertTrue("Check result 'row' as Tuple", Tuple.class.isInstance(resultElement)); Tuple resultElementTuple = (Tuple) resultElement; Object[] tupleArray = resultElementTuple.toArray(); assertEquals(2, tupleArray.length); assertEquals(tupleArray[0], resultElementTuple.get(0)); assertEquals(resultElementTuple.get(namePath), resultElementTuple.get(0)); assertEquals(tupleArray[1], resultElementTuple.get(1)); assertEquals(resultElementTuple.get(agePath), resultElementTuple.get(1)); assertEquals(resultElementTuple.get(agePath), resultElementTuple.get("age")); em.getTransaction().commit(); em.close(); em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); em.createQuery("delete Customer").executeUpdate(); em.getTransaction().commit(); em.close(); }
@Test public void testIllegalArgumentExceptionBuildingTupleWithSameAliases() { EntityManager em = entityManagerFactory().createEntityManager(); em.getTransaction().begin(); final CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<Tuple> criteria = builder.createTupleQuery(); Root<Customer> customerRoot = criteria.from(Customer.class); Path<String> namePath = customerRoot.get(Customer_.name); namePath.alias("age"); Path<Integer> agePath = customerRoot.get(Customer_.age); agePath.alias("age"); try { criteria.multiselect(namePath, agePath); fail( "Attempt to define multi-select with same aliases should have thrown IllegalArgumentException"); } catch (IllegalArgumentException expected) { } em.getTransaction().commit(); em.close(); }
/** * This query demonstrates a query for multiple properties -- same as above -- except this example * used a Tuple return type and select aliases */ @Test public void testMultiSelectTuple() { log.info("*** testMultiSelectTuple() ***"); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> qdef = cb.createTupleQuery(); // select c.firstName as firstName, c.hireDate as hireDate from Clerk c Root<Clerk> c = qdef.from(Clerk.class); qdef.select( cb.tuple(c.get("firstName").alias("firstName"), c.get("hireDate").alias("hireDate"))); TypedQuery<Tuple> query = em.createQuery(qdef); List<Tuple> results = query.getResultList(); assertTrue("no results", results.size() > 0); for (Tuple result : results) { assertEquals("unexpected result length", 2, result.getElements().size()); String firstName = result.get("firstName", String.class); Date hireDate = result.get("hireDate", Date.class); log.info("firstName=" + firstName + " hireDate=" + hireDate); } }
public static <T> List<T> queryEntities(EntityManager em, Class<T> entity, QueryParameters q) { if (q == null) throw new IllegalArgumentException( "Query parameters can't be null. " + "If you don't have any parameters either pass a empty object or " + "use the queryEntities(EntityManager, Class<T>) method."); log.finest("Querying entity: '" + entity.getSimpleName() + "' with parameters: " + q); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(entity); CriteriaQuery<Tuple> ct = cb.createTupleQuery(); Root<T> r = cq.from(entity); Root<T> rt = ct.from(entity); if (!q.getFilters().isEmpty()) { Predicate whereQuery = createWhereQuery(cb, r, q); Predicate whereQueryTuple = createWhereQuery(cb, rt, q); cq.where(whereQuery); ct.where(whereQueryTuple); } if (!q.getOrder().isEmpty()) { List<Order> orders = createOrderQuery(cb, r, q); List<Order> ordersTuple = createOrderQuery(cb, rt, q); cq.orderBy(orders); ct.orderBy(ordersTuple); } cq.select(r); ct.multiselect(createFieldsSelect(rt, q, getEntityIdField(em, entity))); TypedQuery<T> tq = em.createQuery(cq); TypedQuery<Tuple> tqt = em.createQuery(ct); if (q.getLimit() != null && q.getLimit() > -1) { tq.setMaxResults(q.getLimit().intValue()); tqt.setMaxResults(q.getLimit().intValue()); } if (q.getOffset() != null && q.getOffset() > -1) { tq.setFirstResult(q.getOffset().intValue()); tqt.setFirstResult(q.getOffset().intValue()); } if (q.getFields().isEmpty()) { return tq.getResultList(); } else { return createEntityFromTuple(tqt.getResultList(), entity); } }