我刚刚在github上找到了Hibernate的@ManyToMany关系的示例,这使我想知道什么是实现它的正确方法。让我更好地解释。用例非常简单:我有一个可以扮演一个或多个角色的用户。我最初以为这种关系是多对多的关系,但是我发现这个例子使我很困惑:
Users.java类
@Entity
@Table(name = "user")
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "user_id")
private int id;
@Column(name = "email")
private String email;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
public Users() {
}
public Users(Users users) {
this.email = users.getEmail();
this.roles = users.getRoles();
this.id = users.getId();
}
`// getters and setters
Role.java类
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private int roleId;
@Column(name = "role")
private String role;
public Role() {
}
// getters and setters
首先,它使用OneToMany关系(我无法解释原因),其次,它在Role类中没有对Users的引用。有人知道为什么并且可以向我解释吗?我本来可以处理ManyToMany关系,并且可以在Role内部使用@ManyToMany批注来放置一组用户。 Here the link to the git repo。