我想通过ManyToMany关联两个实体。我找到了很多例子(比如这个https://en.wikibooks.org/wiki/Java_Persistence/ManyToMany#Example_of_a_ManyToMany_relationship_annotation或https://vladmihalcea.com/the-best-way-to-use-the-manytomany-annotation-with-jpa-and-hibernate/),甚至在我的代码中有一个其他地方,其中ManyToMany关系似乎有效,但到目前为止我仍然无法想到这一点
我遇到以下异常:
引起:org.hibernate.MappingException:外键(FKru66hm0369ayn8dvjj2rgxr9v:user_role [role_id]))必须与引用的主键具有相同的列数(user_role [user_id,role_id])
班级用户
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue
@Column(name = "user_id")
private long id;
@ManyToMany
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
// getters and setters
}
班级角色
@Entity
@Table(name = "user_role")
public class Role {
@Id
@GeneratedValue
@Column(name = "role_id")
private long id;
@ManyToMany(mappedBy = "roles")
private Set<User> users;
// getters and setters
}
答案 0 :(得分:1)
检查this link!
无论如何,问题是你有类角色
@Entity
@Table(name = "user_role")
public class Role {
以及类用户
@JoinTable(
name = "user_role",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
两个地方,表名都相同......
那一定是错误的原因......