【问题标题】:HQL query for non-standard ManyToMany relationship非标准多对多关系的 HQL 查询
【发布时间】:2012-05-23 02:31:09
【问题描述】:

作者图书之间存在多对多关系。
表:作者
id |姓名

表:分配
*id |作者_id | book_id*

表:BOOK
id |标题

但我使用的不是标准的多对多映射,我正在使用下一个

class Book
{
   @Id
   long id;

   String title;

   @OneToMany
   List<Assign> authors;
}

class Assign
{
   @Id
   long id;

   @ManyToOne
   Book book

   @ManyToOne
   Author author;
}

class Author
{
   @Id
   long id;

   String name;

   @OneToMany
   List<Assign> books;
}  

什么是获取作者姓名的所有书籍的查询?还有什么是查询来获取作者姓名的所有书籍名称?

【问题讨论】:

    标签: java hibernate jpa hql


    【解决方案1】:

    您只有两个 OneToMany 关联。您只需在查询中使用联接,如Hibernate documentation over HQL 中所述。

    select book from Author author 
    left join author.books assign
    left join assign.book book
    where author.name = :name
    

    第二个查询是一样的,只是你只需要书名:

    select book.name from Author author ...
    

    旁注:您不应该将您的分配集合命名为booksauthors:这非常令人困惑。将其命名为assigns

    【讨论】:

    • 最后是 ' where book.title = :title '。是的,这是真的
    【解决方案2】:

    什么是查询作者姓名的所有书籍?

    来自 b.authors.author.name 的书 b 订单

    什么是查询以获取所有书籍的作者姓名?

    从 b.authors.author.name 的 Book b order 中选择 b.title

    您是否在 Author 和 Book 类中交换了标题和名称?

    【讨论】:

      猜你喜欢
      • 2015-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-03
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多