User
和
Role
实体。
我能够实现这一点,使用下面的代码,但在我的要求,我需要
一个额外的列
在透视表中(
users_to_role
).
@ManyToMany
@JoinTable(
name = "users_to_roles",
joinColumns = @JoinColumn(
name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(
name = "role_id", referencedColumnName = "id"))
private List<Role> roles;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
@OneToMany(mappedBy="users", cascade = CascadeType.ALL)
private List<Role> roles;
//getters and setters here
}
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@OneToMany(mappedBy="roles", cascade = CascadeType.ALL)
private List<User> users;
//getters and setters here
}
用户角色.java
@Entity
@Table(name = "users_to_role")
public class UserRole {
@Id
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@Id
@ManyToOne
@JoinColumn(name = "role_id")
private Role role;
private Date createdAt;
//getters and setters here
}
下面是错误堆栈:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Illegal use of mappedBy on both sides of the relationship: com.example.entities.Role.users