JPA/Criteria API – Like & equal problem

Perhaps you need criteria.add(cb.like(emp.<String>get(“name”), p)); because first argument of like() is Expression<String>, not Expression<?> as in equal(). Another approach is to enable generation of the static metamodel (see docs of your JPA implementation) and use typesafe Criteria API: criteria.add(cb.like(emp.get(Employee_.name), p)); (Note that you can’t get static metamodel from em.getMetamodel(), you need to generate it by … Read more

Compare Date entities in JPA Criteria API

The problem is that with the string-based API it cannot infer the type for the result value of the get-Operation. This is explained for example in Javadoc for Path. If you use predicates.add(builder.lessThanOrEqualTo(root.<Date>get(“dateCreated”), param)); instead, it will work fine, because it can figure out the return type from the type argument and will find out … Read more

JPA 2.0, Criteria API, Subqueries, In Expressions

Below is the pseudo-code for using sub-query using Criteria API. CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(); Root<EMPLOYEE> from = criteriaQuery.from(EMPLOYEE.class); Path<Object> path = from.get(“compare_field”); // field to map with sub-query from.fetch(“name”); from.fetch(“id”); CriteriaQuery<Object> select = criteriaQuery.select(from); Subquery<PROJECT> subquery = criteriaQuery.subquery(PROJECT.class); Root fromProject = subquery.from(PROJECT.class); subquery.select(fromProject.get(“requiredColumnName”)); // field to map with main-query subquery.where(criteriaBuilder.and(criteriaBuilder.equal(“name”,name_value),criteriaBuilder.equal(“id”,id_value))); select.where(criteriaBuilder.in(path).value(subquery)); … Read more

JPA Criteria Query API and order by two columns

If you need to add couple of orders you can make something like (but for your query and different root objects) CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Route> query = criteriaBuilder.createQuery(Route.class); Root<Route> routeRoot = query.from(Route.class); query.select(routeRoot); List<Order> orderList = new ArrayList(); query.where(routeRoot.get(“owner”).in(user)); orderList.add(criteriaBuilder.desc(routeRoot.get(“date”))); orderList.add(criteriaBuilder.desc(routeRoot.get(“rating”))); query.orderBy(orderList);

JPA & Criteria API – Select only specific columns

One of the JPA ways for getting only particular columns is to ask for a Tuple object. In your case you would need to write something like this: CriteriaQuery<Tuple> cq = builder.createTupleQuery(); // write the Root, Path elements as usual Root<EntityClazz> root = cq.from(EntityClazz.class); cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION)); //using metamodel List<Tuple> tupleResult = em.createQuery(cq).getResultList(); for (Tuple t … Read more