Search in sources :

Example 1 with TypedQuery

use of javax.persistence.TypedQuery in project robo4j by Robo4J.

the class DefaultRepository method findByFields.

@SuppressWarnings("unchecked")
@Override
public <T> List<T> findByFields(Class<T> clazz, Map<String, Object> map, int limit, SortType sort) {
    EntityManager em = dataSourceContext.getEntityManager(clazz);
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery(clazz);
    Root<T> rs = cq.from(clazz);
    List<Predicate> predicates = map.entrySet().stream().map(e -> cb.equal(rs.get(e.getKey()), e.getValue())).collect(Collectors.toList());
    CriteriaQuery<T> cq2 = cq.where(predicates.toArray(new Predicate[predicates.size()])).orderBy(getOrderById(cb, rs, sort)).select(rs);
    TypedQuery<T> tq = em.createQuery(cq2);
    //@formatter:off
    return tq.setMaxResults(limit).getResultList();
//@formatter:on
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) List(java.util.List) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Predicate(javax.persistence.criteria.Predicate) Map(java.util.Map) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Order(javax.persistence.criteria.Order) SortType(com.robo4j.db.sql.support.SortType) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) TypedQuery(javax.persistence.TypedQuery) DataSourceContext(com.robo4j.db.sql.support.DataSourceContext) Root(javax.persistence.criteria.Root) EntityManager(javax.persistence.EntityManager) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Predicate(javax.persistence.criteria.Predicate)

Example 2 with TypedQuery

use of javax.persistence.TypedQuery in project hibernate-orm by hibernate.

the class ExpressionsTest method testParameterReuse.

@Test
public void testParameterReuse() {
    EntityManager em = getOrCreateEntityManager();
    em.getTransaction().begin();
    CriteriaQuery<Product> criteria = em.getCriteriaBuilder().createQuery(Product.class);
    Root<Product> from = criteria.from(Product.class);
    ParameterExpression<String> param = em.getCriteriaBuilder().parameter(String.class);
    Predicate predicate = em.getCriteriaBuilder().equal(from.get(Product_.id), param);
    Predicate predicate2 = em.getCriteriaBuilder().equal(from.get(Product_.name), param);
    criteria.where(em.getCriteriaBuilder().or(predicate, predicate2));
    assertEquals(1, criteria.getParameters().size());
    TypedQuery<Product> query = em.createQuery(criteria);
    int hqlParamCount = countGeneratedParameters(query.unwrap(Query.class));
    assertEquals(1, hqlParamCount);
    query.setParameter(param, "abc").getResultList();
    em.getTransaction().commit();
    em.close();
}
Also used : EntityManager(javax.persistence.EntityManager) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(org.hibernate.Query) Product(org.hibernate.jpa.test.metamodel.Product) Predicate(javax.persistence.criteria.Predicate) Test(org.junit.Test) AbstractMetamodelSpecificTest(org.hibernate.jpa.test.metamodel.AbstractMetamodelSpecificTest)

Example 3 with TypedQuery

use of javax.persistence.TypedQuery in project microservices by pwillhan.

the class CreateExecuteQueries method createQueries.

@Test
public void createQueries() throws Exception {
    storeTestData();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            Query query = em.createQuery("select i from Item i");
            assertEquals(query.getResultList().size(), 3);
        }
        {
            CriteriaBuilder cb = em.getCriteriaBuilder();
            // Also available on EntityManagerFactory:
            // CriteriaBuilder cb = entityManagerFactory.getCriteriaBuilder();
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(criteria.from(Item.class));
            Query query = em.createQuery(criteria);
            assertEquals(query.getResultList().size(), 3);
        }
        {
            // Note: This old JPA 1.0 method does not return a TypedQuery!
            Query query = em.createNativeQuery("select * from ITEM", Item.class);
            assertEquals(query.getResultList().size(), 3);
        }
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) Test(org.testng.annotations.Test)

Example 4 with TypedQuery

use of javax.persistence.TypedQuery in project microservices by pwillhan.

the class Restriction 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();
        {
            // select i from Item i where i.name = 'Foo'
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.equal(i.get("name"), "Foo"));
            TypedQuery<Item> q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
            assertEquals(q.getResultList().iterator().next().getName(), "Foo");
        }
        em.clear();
        {
            // Equals boolean
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).where(cb.equal(u.get("activated"), true));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            // Between
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(cb.between(// Type of path required!
            b.<BigDecimal>get("amount"), // Must be same type!
            new BigDecimal("99"), // Must be same type!
            new BigDecimal("110")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Greater than
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(// gt() only works with Number, use greaterThan() otherwise!
            cb.gt(b.<BigDecimal>get("amount"), new BigDecimal("100")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // Greater than with date (!Number)
            Date tomorrowDate = CalendarUtil.TOMORROW.getTime();
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.greaterThan(i.<Date>get("auctionEnd"), tomorrowDate));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // IN list
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).where(cb.<String>in(u.<String>get("username")).value("johndoe").value("janeroe"));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            // Enum
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.equal(i.<AuctionType>get("auctionType"), AuctionType.HIGHEST_BID));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Ternary operators
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.isNull(i.get("buyNowPrice")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.isNotNull(i.get("buyNowPrice")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // String matching
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).where(cb.like(u.<String>get("username"), "john%"));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        {
            // String matching
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).where(cb.like(u.<String>get("username"), "john%").not());
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).where(cb.like(u.<String>get("username"), "%oe%"));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.like(i.<String>get("name"), "Name\\_with\\_underscores", '\\'));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 0);
        }
        em.clear();
        {
            // Arithmetic
            CriteriaQuery criteria = cb.createQuery();
            Root<Bid> b = criteria.from(Bid.class);
            criteria.select(b).where(cb.gt(cb.diff(cb.quot(b.<BigDecimal>get("amount"), 2), 0.5), 49));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            // Logical groups
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            Predicate predicate = cb.and(cb.like(i.<String>get("name"), "Fo%"), cb.isNotNull(i.get("buyNowPrice")));
            predicate = cb.or(predicate, cb.equal(i.<String>get("name"), "Bar"));
            criteria.select(i).where(predicate);
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.like(i.<String>get("name"), "Fo%"), // AND
            cb.isNotNull(i.get("buyNowPrice")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // Collection functions
            CriteriaQuery criteria = cb.createQuery();
            Root<Category> c = criteria.from(Category.class);
            criteria.select(c).where(cb.isNotEmpty(c.<Collection>get("items")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            // Collection functions
            CriteriaQuery criteria = cb.createQuery();
            Root<Category> c = criteria.from(Category.class);
            criteria.select(c).where(cb.isMember(cb.parameter(Item.class, "item"), c.<Collection<Item>>get("items")));
            Query q = em.createQuery(criteria);
            Item item = em.find(Item.class, testData.items.getFirstId());
            q.setParameter("item", item);
            List<Category> result = q.getResultList();
            assertEquals(result.size(), 1);
        }
        em.clear();
        {
            // Collection functions
            CriteriaQuery criteria = cb.createQuery();
            Root<Category> c = criteria.from(Category.class);
            criteria.select(c).where(cb.gt(cb.size(c.<Collection>get("items")), 1));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // Calling functions
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i).where(cb.like(cb.lower(i.<String>get("name")), "ba%"));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            // Ordering result
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).orderBy(cb.desc(u.get("username")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Ordering result
            CriteriaQuery criteria = cb.createQuery();
            Root<User> u = criteria.from(User.class);
            criteria.select(u).orderBy(cb.desc(u.get("activated")), cb.asc(u.get("username")));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserTransaction(javax.transaction.UserTransaction) User(org.jpwh.model.querying.User) Category(org.jpwh.model.querying.Category) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) BigDecimal(java.math.BigDecimal) Date(java.util.Date) Predicate(javax.persistence.criteria.Predicate) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) Collection(java.util.Collection) List(java.util.List) Bid(org.jpwh.model.querying.Bid) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Example 5 with TypedQuery

use of javax.persistence.TypedQuery in project microservices by pwillhan.

the class Selection method executeQueries.

@Test
public void executeQueries() throws Exception {
    storeTestData();
    CriteriaBuilder cb = JPA.getEntityManagerFactory().getCriteriaBuilder();
    // or:
    // CriteriaBuilder cb = em.getCriteriaBuilder();
    UserTransaction tx = TM.getUserTransaction();
    try {
        tx.begin();
        EntityManager em = JPA.createEntityManager();
        {
            // This is not guaranteed to work in all JPA providers, criteria.select() should be used
            CriteriaQuery criteria = cb.createQuery(Item.class);
            criteria.from(Item.class);
            List<Item> result = em.createQuery(criteria).getResultList();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            // Simplest
            CriteriaQuery criteria = cb.createQuery();
            Root<Item> i = criteria.from(Item.class);
            criteria.select(i);
            List<Item> result = em.createQuery(criteria).getResultList();
            assertEquals(result.size(), 3);
        }
        em.clear();
        {
            // Nested calls
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(criteria.from(Item.class));
            TypedQuery<Item> q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Restrict type with metamodel
            CriteriaQuery criteria = cb.createQuery();
            EntityType entityType = getEntityType(em.getMetamodel(), "Item");
            criteria.select(criteria.from(entityType));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 3);
        }
        em.clear();
        {
            // Polymorphism restricted types
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(criteria.from(BillingDetails.class));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 2);
        }
        em.clear();
        {
            CriteriaQuery criteria = cb.createQuery();
            criteria.select(criteria.from(CreditCard.class));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // Polymorphism restricted types
            CriteriaQuery criteria = cb.createQuery();
            Root<BillingDetails> bd = criteria.from(BillingDetails.class);
            criteria.select(bd).where(cb.equal(bd.type(), CreditCard.class));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
        }
        em.clear();
        {
            // Polymorphism restricted types
            CriteriaQuery criteria = cb.createQuery();
            Root<BillingDetails> bd = criteria.from(BillingDetails.class);
            criteria.select(bd).where(cb.not(cb.equal(bd.type(), BankAccount.class)));
            Query q = em.createQuery(criteria);
            assertEquals(q.getResultList().size(), 1);
            assertTrue(q.getResultList().iterator().next() instanceof CreditCard);
        }
        em.clear();
        {
            // Polymorphism restricted types
            CriteriaQuery criteria = cb.createQuery();
            Root<BillingDetails> bd = criteria.from(BillingDetails.class);
            criteria.select(bd).where(bd.type().in(cb.parameter(List.class, "types")));
            Query q = em.createQuery(criteria);
            q.setParameter("types", Arrays.asList(CreditCard.class, BankAccount.class));
            assertEquals(q.getResultList().size(), 2);
        }
        tx.commit();
        em.close();
    } finally {
        TM.rollback();
    }
}
Also used : CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) UserTransaction(javax.transaction.UserTransaction) Root(javax.persistence.criteria.Root) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) TypedQuery(javax.persistence.TypedQuery) Query(javax.persistence.Query) TypedQuery(javax.persistence.TypedQuery) CriteriaQuery(javax.persistence.criteria.CriteriaQuery) BankAccount(org.jpwh.model.inheritance.tableperclass.BankAccount) BillingDetails(org.jpwh.model.inheritance.tableperclass.BillingDetails) CreditCard(org.jpwh.model.inheritance.tableperclass.CreditCard) EntityType(javax.persistence.metamodel.EntityType) Item(org.jpwh.model.querying.Item) EntityManager(javax.persistence.EntityManager) List(java.util.List) Test(org.testng.annotations.Test) QueryingTest(org.jpwh.test.querying.QueryingTest)

Aggregations

TypedQuery (javax.persistence.TypedQuery)37 EntityManager (javax.persistence.EntityManager)22 List (java.util.List)16 CriteriaQuery (javax.persistence.criteria.CriteriaQuery)16 CriteriaBuilder (javax.persistence.criteria.CriteriaBuilder)14 Query (javax.persistence.Query)13 ArrayList (java.util.ArrayList)8 Root (javax.persistence.criteria.Root)8 UserTransaction (javax.transaction.UserTransaction)8 Item (org.jpwh.model.querying.Item)8 Test (org.testng.annotations.Test)8 Collectors (java.util.stream.Collectors)6 EntityTransaction (javax.persistence.EntityTransaction)6 BigDecimal (java.math.BigDecimal)5 Date (java.util.Date)5 Map (java.util.Map)4 Set (java.util.Set)4 Predicate (javax.persistence.criteria.Predicate)4 Test (org.junit.Test)4 Collection (java.util.Collection)3