2015-11-02 55 views
-1

我在db中有3個表。我正在嘗試編寫JPA實體。我正在面對關聯表實體的一些問題。我的實體有:如何將關聯表定義爲pojo實體

Person.java

@Entity 
@Table(name = "person") 
public class Person { 

    @Id 
    @GeneratedValue 
    private Long id; 

    @Column(nullable = false) 
    private String firstName; 

    @Column(nullable = false) 
    private String lastName; 
//setter and getter 
} 

Exam.java

@Entity 
@Table(name = "exam") 
public class Exam { 
    @Id 
    @GeneratedValue 
    private long examId; 

    @Column(nullable = false) 
    private String examName; 

    @Column(nullable = false) 
    private int marks; 
    //Setters and getters 
} 

的關聯表的表結構,

create table person_exam (
     personId BIGINT not null, 
     examId BIGINT not null, 
     primary key (personId, examId) 
    ); 

我試過聯想ation表實體和@ManyToMany註解,這兩個屬性都不給我結果。

任何人都可以請我建議我需要什麼,我需要使用(ManyToMany/OneToOne/ManyToOne/OneToMany)在我的實體上述person_exam表。

+0

所有JPA實現都具有足以解釋如何具有1-N/M-N關係的文檔。建議你閱讀一個 –

回答

0

來自PRO JPA 2nd Ed。書:

實現多對多關係的唯一方法是使用單獨的連接表。在任何一個實體表中沒有任何連接列的結果是,沒有辦法確定哪一方是關係的所有者。因爲每一個雙向關係都必須有一個擁有方和一個相反方,所以我們必須選擇兩個實體中的一個作爲所有者。

所以我選擇了Person實體。將所需的更改應用到不完整的代碼中:

@Entity 
@Table(name = "person") 
public class Person { 

    @Id 
    @GeneratedValue 
    private Long id; 

    @Column(nullable = false) 
    private String firstName; 

    @Column(nullable = false) 
    private String lastName; 

    /** 
    * we need to add some additional metadata to the Person designated 
    * as the owner of the relationship, also you must fully specify the names of 
    * the join table and its columns because you already provided a schema 
    * for the association table, otherwise the JPA provider would generate one. 
    */ 
    @ManyToMany 
    @JoinTable(name="person_exam", 
    [email protected](name="personId"), 
    [email protected](name="examId")) 
    private Collection<Exams> exams; 

//setter and getter 
} 

@Entity 
@Table(name = "exam") 
public class Exam { 
    @Id 
    @GeneratedValue 
    private long examId; 

    @Column(nullable = false) 
    private String examName; 

    @Column(nullable = false) 
    private int marks; 
    //Setters and getters 


    /** 
    * As in every other bidirectional relationship, 
    * the inverse side must use the mappedBy element to identify 
    * the owning attribute. 
    */ 
    @ManyToMany(mappedBy="exams") 
    private Collection<Person> people; 
}