2014-09-29 92 views
0

如何創建下列情況下的註釋:休眠:連接表連接表的註釋

Table A 
id 
name 

Table B 
id 
name 

Table C 
id 
name 

Table AB 
a_id 
b_id 

Table ABC 
id 
a_id 
b_id 
c_id 
name 

你怎麼能使用註解休眠代表表ABC?

表AB是不是被用作表的對象表A和B.

爲A和B的註釋之間的連接會看起來像這樣:

用於:

@OneToMany(cascade=CascadeType.ALL) 
@JoinTable(name="AB", 
joinColumns={@JoinColumn(name="a_id", referencedColumnName="id")}, 
inverseJoinColumns={@JoinColumn(name="b_id", referencedColumnName="id")}) 
private Set bs; 

對於B:

@OneToMany(cascade=CascadeType.ALL) 
@JoinTable(name="AB", 
joinColumns={@JoinColumn(name="b_id", referencedColumnName="id")}, 
inverseJoinColumns={@JoinColumn(name="a_id", referencedColumnName="id")}) 
private Set as; 

由於提前。

+0

爲什麼不使用@ManyToMany? – Julien 2014-09-29 12:01:38

回答

3

我會做這樣的事情:

答:

@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY) 
@JoinTable(name = "AB", joinColumns = @JoinColumn(name = "A_ID", 
     referencedColumnName = "ID"), inverseJoinColumns = @JoinColumn(name = "B_ID", 
     referencedColumnName = "ID")) 
private List<B> bs; 

同爲B.

ABC:

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "A_ID") 
private A a; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "B_ID") 
private B b; 

@ManyToOne(fetch = FetchType.LAZY) 
@JoinColumn(name = "C_ID") 
private C c; 
+0

嗨Nunien,今天晚些時候會嘗試這個,如果它有效的話,它會標記爲答案!謝謝@Nunien謝謝 – 2014-09-29 21:31:31

+0

偉大的工作 – 2014-09-30 01:50:15