【问题标题】:Can't convert MySql Query(ManyToMany relationship) to HQL无法将 MySql 查询(ManyToMany 关系)转换为 HQL
【发布时间】:2023-03-23 17:31:01
【问题描述】:

有 3 个实体:1)问题,2)它们之间的标签和连接表 - 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);

我对连接表和集合感到困惑。将一个转换成另一个

如果您需要更多代码或信息,请告诉我

【问题讨论】:

    标签: mysql sql spring hibernate jpa


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2013-07-02
      • 2014-06-26
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      相关资源
      最近更新 更多