簡體   English   中英

多對多單向和雙向映射休眠的輸出

[英]output of many-to-many unidirectional and bidirectional mapping hibernate

在休眠狀態下一對一關系的情況下,我們可以看到單向和雙向情況下輸出表存在差異,即只有一個表具有單向關聯的外鍵,並且兩個表都具有外鍵如果是雙向的。 但是我看不到多對多單向和雙向輸出表的任何區別。 有人可以幫我嗎? 謝謝。

實際上,使用多對多單向和雙向時的表數是相同的。 主要的不同是使用雙向對象時,可以獲取列表或在兩側設置對象。 使用單向,您只需要從代碼的一側進行操作即可。 讓我們看一個例子書和作者。 一本書有很多作者,作者可以寫很多本書。 在示例中,我使用了Set,但是您可以使用List。 也可以 讓我們看一下單向映射的映射:

@Entity  
public class Author  
{  
    private Long authorId;  
    private String authorName;  
    private Date dateOfBirth;  

    @Id  
    @GeneratedValue(strategy=GenerationType.AUTO)  
    public Long getAuthorId()  
    {  
        return authorId;  
    }  

    public void setAuthorId(Long authorId)  
    {  
        this.authorId = authorId;  
    }  

    @Column(name="author_name")  
    public String getAuthorName()  
    {  
        return authorName;  
    }  

    public void setAuthorName(String authorName)  
    {  
        this.authorName = authorName;  
    }

    /**
     * @return the dateOfBirth
     */
    public Date getDateOfBirth() {
        return dateOfBirth;
    }
    /**
     * @param dateOfBirth the dateOfBirth to set
     */
    public void setDateOfBirth(Date dateOfBirth) {
        this.dateOfBirth = dateOfBirth;
    }
}  


    @Entity  
public class Book  
{  
  private Long bookId;  
  private String bookTitle;  
  private List<Author> authors;  

  @Id  
  @GeneratedValue(strategy=GenerationType.AUTO)  
  public Long getBookId()  
    {  
        return bookId;  
    }  
    public void setBookId(Long bookId)  
    {  
        this.bookId = bookId;  
    }  

    @Column(name="book_title")  
    public String getBookTitle()  
    {  
        return bookTitle;  
    }  
    public void setBookTitle(String bookTitle)  
    {  
        this.bookTitle = bookTitle;  
    }  
    @ManyToMany(cascade=CascadeType.ALL)  
    @JoinTable(name="author_book", joinColumns=@JoinColumn(name="book_id"), inverseJoinColumns=@JoinColumn(name="author_id"))  
    public List<Author> getAuthors()  
    {  
        return authors;  
    }  
    public void setAuthors(List<Author> authors)  
    {  
        this.authors = authors;  
    }  
}  

您可以看到第三個表是使用兩個表簿和author中的兩個鍵創建的author_book。 因此,使用“單向”,“作者”列表只能從“書”中獲取。 使用雙向,您可以從“作者”訪問“書籍”,也可以從“書籍”訪問“作者”。 Book對象的映射應該相同。 作者看起來有點不同:

@Entity  
public class Author  
{  

    private Set<Book> books;  

    /**
     * @return the books
     */
    public Set<Book> getBooks() {
        return books;
    }

    /**
     * @param books the books to set
     */
    public void setBooks(Set<Book> books) {
        this.books = books;
    }
//the rest is the same code like above
...

}

希望對您清楚!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM