提问者:小点点

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


有3个实体:1)Question,2)Tag和它们之间的连接表-Question_Has_Tag

除联接表外,Java中的对象相同。 取而代之的是:

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;

要转换的查询是:

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);

我混淆了联接表和集合。 把一个转化成另一个

如果你需要更多的代码或信息,请让我知道


共1个答案

匿名用户

试试这个:

@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;
}

和存储库:

@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);
}