Hibernate中的ManyToMany实现并不能正常工作

时间:2016-06-15 13:33:48

标签: java hibernate many-to-many

我想在两个类之间建立关系多对多。 我有这样的课程 - " Room":

@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...

上课&#34;展览&#34;:

@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...

我试图做关系ManyToMany。我在Hibernate文档中从JPA 2.1 JavaDoc中获取了一个示例,它没有工作(它创建了空表&#34; EXHIBITION_ROOM&#34;内部没有id)。像OneToOne这样的其他任何关系都是正常的,也是继承。我该怎么办?

1 个答案:

答案 0 :(得分:0)

你走在正确的轨道上,但你只是告诉roomList加入一张桌子,而不是怎么做。 请看这个示例here

具体在:

@ManyToMany 
@JoinTable(name="EMP_PROJ", 
      joinColumns=@JoinColumn(name="EMP_ID"),
      inverseJoinColumns=@JoinColumn(name="PROJ_ID"))

E.g。此外,您需要指定链接这两个实体的ID。 在你的情况下,它将像

@JoinTable(name="EXHIBITION_ROOM", 
joinColumns=@JoinColumn(name="EXHIBITION_ID"),
inverseJoinColumns=@JoinColumn(name="ROOM_NUMBER"))

不确定名称,因为我不知道你的牌子的名字。但是试一试,也许还可以使用这些名称。