2013-01-14 36 views
1

我有两个实体,Book和Author。用于搜索的HQL查询(一对多关系)

@Entity 
@Table(name="book") 
class Book { 
    private int id; 
    private Map<Integer, Author> authors = new HashMap<Integer, Author>(); 

    @Id 
    @GeneratedValue 
    @Column(name="id_book") 
    public int getId() { 
     return this.id; 
    } 

    @OneToMany(fetch=FetchType.EAGER) 
    @JoinTable(name="book_author", joinColumns= {@JoinColumn(name="id_book")}, 
      inverseJoinColumns = {@JoinColumn(name="id_author", table="author")}) 
    @MapKeyColumn(name="order") 
    public Map<Integer, Author> getAuthors() { 
     return authors; 
    } 


} 

@Entity 
@Table(name="author") 
class Author { 

    private int id; 
    private String lastname; 
    private String firstname; 

    @Id 
    @Column(name="id_author") 
    @GeneratedValue 
    public int getId() { 
     return id; 
    } 

    public String getLastname() { 
     return lastname; 
    } 

    public String getFirstname() { 
     return firstname; 
    } 

} 

一本书有许多作者按特定顺序列出。现在我正在尝试创建一个HQL,以便我可以从特定作者那里获取特定姓氏或姓氏或两者的书籍列表。我很困惑如何使用两个实体之间的连接。任何想法?

在此先感谢。

回答

3

第一:书籍和作者之间有一对多的关系。一本书可以有很多作者,但是一个作者只能写一本书。如果一个真人写了很多书,那么他在书桌作者中需要很多行,每个书都有一行。这可能不是你想要的,但是你已经定义了这样的关系。

一对多关系在表格作者中使用书的id在数据库端工作。通过在Author中创建一个吸气器getBookID(),使该ID在Java中可用。然后你可以使用的HQL语句

from Book b inner join Author a 
    where b.id = a.bookId 
     and a.lastname = :ln 
     and a.firstname = :fn 

from Book b where b.id in (select bookId from Author a 
           where a.lastname = :ln 
           and a.firstname = :fn) 

二:现在,你可能更喜欢一个作者可以有很多书。那么你有一个多对多的关系。为此,建议引入一个包含多对多关系的交叉表。这个交叉表只包含两列,书号和作者ID,书和作者都有一对多的关系(作者没有bookId了)。 HQL语句与第一种情况相似,只不过它们超过了三个表。

编辑:使用您的Book_Author表: 对于您的选择,您必须创建映射到该表的BookAuthor类。 然后,您可以使用的HQL语句

from Book b inner join BookAuthor ba inner join Author a 
    where b.id = ba.bookId 
     and ba.authorId = a.id 
     and a.lastname = :ln 
     and a.firstname = :fn 

from Book b where b.id in (select ba.bookId from BookAuthorba, Author a 
           where ba.authorId = a.id 
           and a.lastname = :ln 
           and a.firstname = :fn) 
+0

,因为我不想绑定笔者到某本书作为一个作家可以写很多书我没在笔者添加任何idBook 。其实我的困惑是我如何链接三个表格,因为我有一个作者类和一个Book类,他们的链接在数据库的book_author表中定义。我不明白他们是如何在课堂上表现的,或者我如何在HQL中表现他们。任何想法? – suenda

+0

我编辑了我的答案。往上看;你必须为连接表创建一个类。 – Johanna

+0

感谢您的帮助。我希望没有创建BookAuthor,但似乎我必须创建它,我会这样做。再次感谢您的帮助 – suenda