MappingException:外键必须与引用的主键具有相同的列数

时间:2016-06-30 08:54:18

标签: hibernate

我想在对象之间建立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])

任何人都可以帮我找出问题所在吗?

1 个答案:

答案 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_idbook_id匹配。