我想在对象之间建立many-to-many
关系。
我在Book
班:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long book_id;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "UserHibernate", joinColumns = {
@JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "book_id",
nullable = false, updatable = false) })
private Set<User> user;
在User
课程中,我有:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL, mappedBy="user")
private List<Book> books;
我没有其他桌子。我有<property name="hibernate.hbm2ddl.auto" value = "create" />
所以我希望hibernate会为我创建表格。
我得到以下例外:
Caused by: org.hibernate.MappingException: Foreign key (FK_6ipoxvx8h128sx13eysun7r00:UserHibernate [book_id])) must have same number of columns as the referenced primary key (UserHibernate [user_id,book_id])
任何人都可以帮我找出问题所在吗?
答案 0 :(得分:0)
@JoinTable
中间表中指定多对多关系,例如User_BookHibernate
:
@JoinTable(name = "User_BookHibernate", joinColumns = {
@JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "book_id",
nullable = false, updatable = false) })
Hibernate将为您创建3个表。 User_BookHibernate
会将user_id
与book_id
匹配。