简体   繁体   English

Java JPQL,连接表,多对多关系

[英]Java JPQL, join table, many to many relation

We are working on a project in school and we trying to use entity JPA. 我们正在学校进行一个项目,并且尝试使用JPA实体。 We have several tables in our Mysql database and the one we are using is taxonomy, term, campaign and term_campaign_relationship. 我们在Mysql数据库中有几个表,我们正在使用的一个表是分类法,术语,活动和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. 我们希望获得与广告系列相关的所有术语,并按分类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. 我们已将@ManyToMany JPQL与@JoinTable和joinColumns一起使用,从而收到了与该广告系列有关的所有条款。

But how do we get the result filtered by the taxonomy id only? 但是,如何仅通过分类ID过滤结果呢?

The sql statement below shows the result we are looking for... 下面的sql语句显示了我们正在寻找的结果...

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 这是来自我们的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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