How to write Subqueries with In-Expressions in JPA 2.0, Criteria API?

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

Is Select EXISTS() possible in JPQL?

You can do a boolean query using a case expression. As of JPA 2.0 (Java EE 6) you can create a TypedQuery . String query = “select case when (count(*) > 0) then true else false end from ……” TypedQuery<Boolean> booleanQuery = entityManager.createQuery(query, Boolean.class); boolean exists = booleanQuery.getSingleResult(); In JPA 1.0 (Java EE 5) you … Read more

a new object was found through a relationship that was not marked cascade PERSIST

What you had likely done is that you created new instance of Article and and some new instance(s) of HeaderField. These instance(s) of HeaderField were then associated with Article. After that trying to persist Article fails, because as error message says, it refers to new objects and relationship is not marked as PERSIST. Additionally according … Read more

JPA insert statement

There is no INSERT statement in JPA. You have to insert new entities using an EntityManager. The only statements allowed in JPA are SELECT, UPDATE and DELETE.

JPA – Criteria API and EmbeddedId

You need to use path navigation to access the attribute(s) of the Embeddable. Here is an example from the JPA 2.0 specification (using the static metamodel): 6.5.5 Path Navigation … In the following example, ContactInfo is an embeddable class consisting of an address and set of phones. Phone is an entity. CriteriaQuery<Vendor> q = cb.createQuery(Vendor.class); … Read more

Spring Data JPA and Querydsl to fetch subset of columns using bean/constructor projection

Looks like custom repository implementation is the way to go for now until something similar available in spring data. I have gone through http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations Here is my implementation which works. However it would be good to have this method available directly in Spring-Data-JPA Step 1: Intermediate interface for shared behavior public interface CustomQueryDslJpaRepository <T, ID … Read more