简体   繁体   中英

Java JPQL, join table, many to many relation

We are working on a project in school and we trying to use entity JPA. We have several tables in our Mysql database and the one we are using is taxonomy, term, campaign and term_campaign_relationship.

We have made an entity for campaign, term, and taxonomy. We would like to get all the terms that are related to a campaign and filtered by taxonomy id.

We have used the @ManyToMany JPQL with @JoinTable and joinColumns With that we have received all the terms that are related with the campaign.

But how do we get the result filtered by the taxonomy id only?

The sql statement below shows the result we are looking for...

SELECT 
t.id, t.term_name, t.taxonomy_id
FROM
term t
    INNER JOIN
taxonomy ty ON ty.id = t.taxonomy_id
    INNER JOIN
campaign c ON c.id IN (SELECT 
        tc.campaign_id
    FROM term_campaign_relationship tc
    WHERE tc.term_id = t.id
)
WHERE c.id = 1 AND ty.id = 1;

This is from our campaign entity in java

@ManyToMany()
@JoinTable(
  name="term_campaign_relationship",
  joinColumns={@JoinColumn(name="campaign_id", referencedColumnName="id")},
  inverseJoinColumns={@JoinColumn(name="term_id", referencedColumnName="id")})
private Collection<Term> programTypes;

Please advise if we are missing anything...

Is this the solution you looked for?

Query query = entityManager.createQuery("Select tax from taxonomy tax where tax.id = :arg1"); 
query.setParameter("arg1", 1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM