简体   繁体   English

无法将 MySql 查询(多对多关系)转换为 HQL

[英]Can't convert MySql Query(ManyToMany relationship) to HQL

There are 3 entities: 1) Question, 2) Tag and join table between them - Question_Has_Tag有 3 个实体:1)问题,2)它们之间的标记和连接表 - Question_Has_Tag

Same objects in java except join table.除连接表外,java 中的相同对象。 Instead of it are:取而代之的是:

public class Question {
  //
  @ManyToMany(fetch = FetchType.LAZY)
  @JoinTable(name = "question_has_tag",
        joinColumns = @JoinColumn(name = "question_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id"))
  private List<Tag> tags;

public class Tag {
  //
  @ManyToMany(mappedBy = "tags", fetch = FetchType.LAZY)
  @ContainedIn
  private List<Question> questions;

The query to convert is:要转换的查询是:

select * from question as q
   join question_has_tag as qht on q.id = qht.question_id
   where qht.question_id in (select question_id from question_has_tag where tag_id = 1);

I'm confusing between the join table and collections.我对连接表和 collections 感到困惑。 In converting one into another在将一个转换为另一个

If u will need more code or information, please let me know如果您需要更多代码或信息,请告诉我

Try this one:试试这个:

@Entity
public class Question {
    @ManyToMany(mappedBy = "question_has_tag", fetch = FetchType.LAZY)
    private List<Tag> tags;
}

@Entity
public class Tag {
    @ManyToMany(targetEntity = Question.class, fetch = FetchType.LAZY)
    private List<Question> questions;
}

And repository for query results:以及查询结果的存储库:

@Repository
public interface QuestionRepository extends JpaRepository<Question, Integer> {
  @Query("select q from Question q join Tag t where q.id in (:ids)")
  public List<Question> getQuestionsById(@Param("ids") List<Integer> ids);
}

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

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