Dennis Ich
Dennis Ich

Reputation: 3785

JPA Criteria ManyToMany Join or No Join?

i have 2 Entities with the following Metamodels.

@StaticMetamodel(SearchIn.class)
public class SearchIn_ {
    public static volatile SingularAttribute<SearchIn, Integer> id;
    public static volatile SingularAttribute<SearchIn, String> searchString;
    public static volatile SetAttribute<SearchIn, Take> takes;
    // Other Attributes...
}

@StaticMetamodel(Take.class)
public class Take_ {
    public static volatile SingularAttribute<Take, Integer> id;
    // Other Attributes...
}

The relationship is a ManyToMany mapped by SearchIn.Class and Take.Class has no referene to SearchIn.Class.

What i need now is all Takes that are mapped to a SearchIn with a specific searchString. I want to use the criteria api but i can't figure out which entitity i need as Root and how to do the joins with that. I saw some other questions that are similar but not realy what i want and i dont get it to work :/

So can somone give me a Hint and help me to build this up?

Upvotes: 0

Views: 1549

Answers (1)

tagtraeumer
tagtraeumer

Reputation: 1491

Why don't you try a simple join:

Root<SearchIn> root = criteriaQuery.from(SearchIn.class);
Join<SearchIn, Take> takeJoin = root.join(SearchIn_.takes);
criteriaQuery.where(builder.equal(root.get(SearchIn_.searchString), "bla"));


TypedQuery<SearchIn> typedQuery = entityManager.createQuery(criteriaQuery);
return typedQuery.getResultList();

your return value will be a List of SearchIns. and you just call the getet for your Takes. I haven't tried if it's running. I just copied it from some of my code snippets.

Upvotes: 2

Related Questions