網頁

2018/6/22

Hibernate JPA 雙向一對多/多對一設定 Bidirectional One To Many / Many To One

一個作者(Author)有多本書(Book),JPA 雙向一對多/多對一實體關聯設定如下。


Author.java

@Entity
@Table(name="Author")
public class Author {
    
    @Id
    @Column(name="AuthorId")
    private Integer authorId;
    
    @Column(name="AuthorName")
    private String authorName;
    
    @OneToMany(mappedBy="author")
    private Set&t;Book> bookSet;

    // getter and setter ommitted...
}

Book.java

@Entity
@Table(name="Book")
public class Book {
    
    @Id
    @Column(name="BookId")
    private Integer bookId;
    
    @Column(name="BookName")
    private String bookName;
    
    @ManyToOne
    @JoinColumn(name="AuthorId") // 外鍵欄位名稱
    private Author author; // 外鍵屬性

    // getter and setter ommitted...
}

@JoinColumn要放在外鍵所在的實體(owning side)的外鍵屬性。Book持有Author的外鍵,所以@JoinColumn放在Book.author

@OneToMany放在non owning side的實體,並設定mappedBy,其值為關係實體外鍵屬性的名稱。


參考:

沒有留言:

張貼留言