0

I have these (simplified) entities:

@Entity public class Project { @ManyToOne private Type type; } @Entity public class Type { @ManyToOne private Category category; } @Entity public class Category { } 

No I want to query all projects belonging so to selected Types with a CriteriaQuery.

List<Type> types = ... List<Category> categories = ... CriteriaBuilder cB = em.getCriteriaBuilder(); CriteriaQuery<MeisProject> cQ = cB.createQuery(Project.class); Root<Project> project = cQ.from(Project.class); cQ.where(cB.isTrue(project.get("type").in(types))); cQ.select(project).distinct(true); return em.createQuery(cQ).getResultList(); 

This works fine, but how to I add the categories to this query? The category is a property of the type, I want to query all projects

  • belonging to a list of types (working in the example)
  • AND belonging to a type in a list of categories (the reason for this question)
3
  • What should the query do? You haven't said. Commented Jan 24, 2015 at 8:27
  • projects don't have categories, so it can't be similar. Should the query restrict even more by category? should it accept projects that are in the given categories even if they're not in the given types? We can't guess. Be precise. Commented Jan 24, 2015 at 8:55
  • Sorry for the imprecise question. updated: "beloning to a type in a list of categories". the category is a property of the type. We don't have to care if the categories are not in the given types. Commented Jan 24, 2015 at 9:00

1 Answer 1

2

Just as you would need them in JPQL (which I suggest using if the query is a static query, because it's much simpler and more readable), you need joins:

Join<Project, Type> type = project.join("type"); Join<Type, Category> category = type.join("category"); cQ.where(type.in(types), category.in(categories)); 

(not tested)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.