Hi!,
I'm newbie with JPA and I can't help with some JPA Criteria query.
Fragment of my code:
Code:
ArrayList<Predicate> predicates = new ArrayList<Predicate>();
predicates.add(criteriaBuilder.like(commitRoot.<String> get("name"), "%USER_ENTRY%"));
(...)
CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Commit> criteriaQuery = criteriaBuilder.createQuery(Commit.class);
Root<Commit> commitRoot = criteriaQuery.from(Commit.class);
commitRoot.fetch("branches");
criteriaQuery.where(predicates.toArray(new Predicate[] {}));
criteriaQuery.orderBy(criteriaBuilder.desc(commitRoot.get("commitDate")));
TypedQuery<Commit> typedQuery = em.createQuery(criteriaQuery);
List<Commit> results = typedQuery.getResultList();
As my code shows, I want to compare some user entry text with "
name" attribute of "
branches" collection which is fetched with
"Commit" objects.
When I run this code I get :
Code:
java.lang.NullPointerException
org.hibernate.ejb.criteria.path.AbstractPathImpl.unknownAttribute(AbstractPathImpl.java:110)
org.hibernate.ejb.criteria.path.AbstractPathImpl.locateAttribute(AbstractPathImpl.java:218)
org.hibernate.ejb.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:189)
It points to line:
Code:
predicates.add(criteriaBuilder.like(commitRoot.<String> get("name"), "%USER_ENTRY%"));
fragment of Commit.java
Code:
@ManyToMany(cascade = { CascadeType.ALL })
@JoinTable(name = "branch_commit", joinColumns = { @JoinColumn(name = "commitId") }, inverseJoinColumns = { @JoinColumn(name = "branchId") })
public List<Branch> getBranches() {
return branches;
}
fragment of Branch.java:
Code:
@Entity
@Table(name = "branch")
public class Branch implements Serializable, Comparable<Branch> {
private static final long serialVersionUID = 1L;
private Long branchId;
private String name;
What is wrong? I suppose, Hibernate can't see "
name" attribute.
This code also fails with the same exception:
Code:
predicates.add(criteriaBuilder.like(commitRoot.<String> get("branches.name"), "%USER_ENTRY%"));
But, when I run JPQL code like this :
Code:
Query q = em.createQuery("from Commit commit left join fetch commit.branches where name like '%USER_ENTRY%'");
List results2 = q.getResultList();
it works as I expect. How to translate it to Criteria?
Please, help! Thanks in advance!