【问题标题】:How to write a HQL query for a many to many association如何为多对多关联编写 HQL 查询
【发布时间】:2017-03-29 20:56:28
【问题描述】:

所以我花了几个小时尝试为多对多关系编写 HQL 查询。即使在阅读了休眠文档之后,我尝试过的所有查询都没有任何效果。有人可以帮助我吗?提前谢谢你。

我尝试过内连接、连接和外连接,有或没有 fetch。我认为这个问题可能与香水类中的一对多关系有关。

@Query("FROM Category c INNER JOIN FETCH c.fragrances f WITH c.referencedId = 1")
List<Category> getCatalog();

没有 get/setter 的类别类

@Entity
public class Category extends AbstractEntity {

   @Column(name = "name", nullable = false)
   private String name;

   @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
   @JoinTable(name = "Category_has_Fragrance",
        joinColumns = @JoinColumn(name = "category_id"),
        inverseJoinColumns = @JoinColumn(name = "fragrance_id")
   )
   @OrderBy("name")
   private List<Fragrance> fragrances;

   @Column(name = "referenced_id", nullable = false)
   private int referencedId;
]

没有 get/setter 的 Fragrance 类

@Entity
public class Fragrance extends AbstractEntity {

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "description", nullable = false)
    private String description;

    @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrances")
    private Set<Category> categories;

    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "fragrance")
    private List<FragrancedProduct> fragrancedProducts;

    @Column(name = "image_path")
    private String imagePath;
}

【问题讨论】:

标签: hibernate hql


【解决方案1】:

试试这个:

select c from Category c join c.fragrances f where c.referencedId = :id

你可以在这里查看类似的问题:How do I do with HQL, many to many?

【讨论】:

  • 谢谢,我昨晚可能打了几个查询,这些查询本来可以的。您的查询帮助我找到了根本问题。问题是我有一个名为 Set 的表名,并且在我拥有的所有关系中,hibernate 试图从表 Set 中进行选择。我再也不会在列或表名中使用关键字
猜你喜欢
  • 2011-04-18
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
  • 2018-10-07
  • 2015-06-24
  • 2011-08-21
  • 2013-06-08
  • 1970-01-01
相关资源
最近更新 更多