2016-06-15 46 views
0

我想在兩個類之間建立多對多的關係。 我上課這樣的 - 「房間」:Hibernate中的ManyToMany實現無法正常工作

@Entity 
public class Room { 

@Id 
@GeneratedValue 
private long number; 
private boolean state; 

@ManyToMany(mappedBy = "roomList") 
private List<Exhibition> exhibitionList; 

public Room(){ 

} 

public Room(int number, boolean state) { 
    super(); 
    this.number = number; 
    this.state = state; 
} 

...getters and setters... 

和類 「展覽會」:

@Entity 
public class Exhibition { 

@Id 
@GeneratedValue 
private long Id; 
private String title; 
private Date dateOfOpening; 
private Date dataOfEnding; 
private double price; 
private String description; 

@ManyToMany 
@JoinTable(name="EXHIBITION_ROOM") 
private List<Room> roomList; 

public Exhibition(){ 

} 

public Exhibition(String title, Date dateOfOpening, Date dataOfEnding, double price, String description) { 
    super(); 
    this.title = title; 
    this.dateOfOpening = dateOfOpening; 
    this.dataOfEnding = dataOfEnding; 
    this.price = price; 
    this.description = description; 
} 

...geters, setters... 

我試圖做關係多對多。我從Hibernate文檔中的JPA 2.1 JavaDoc中獲取了一個示例,但它不起作用(它創建了空表「EXHIBITION_ROOM」,其中沒有id)。像OneToOne這樣的其他每個關係都可以正常工作,也可以繼承。我該怎麼辦?

回答

0

你在正確的軌道上,但你只告訴roomList加入一張表,而不是如何去做。 看看這個例子here

具體地說於:

@ManyToMany 
@JoinTable(name="EMP_PROJ", 
     [email protected](name="EMP_ID"), 
     [email protected](name="PROJ_ID")) 

例如另外,您需要指定鏈接兩個實體的ID。 在你的情況下,它會像

@JoinTable(name="EXHIBITION_ROOM", 
[email protected](name="EXHIBITION_ID"), 
[email protected](name="ROOM_NUMBER")) 

不知道的名字,因爲我不知道你的表的名稱。但試試這個,或許也可以用名字來玩弄一下。