Bey*_*yli 9 java mysql spring jpa spring-boot
我的 Spring-Boot 应用程序中有两个实体:
用户.java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String firstname;
String lastname;
String username;
String password;
}
Run Code Online (Sandbox Code Playgroud)
和
角色.java
Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
String description;
}
Run Code Online (Sandbox Code Playgroud)
对于我的 MySql 数据库
我已经排除了这个问题的 getter 和 setter 方法。
我想实现两个实体之间的多对多关系。每个用户都应该能够为自己分配多个角色
我已经为我的数据库中的两个表创建了一个映射表。它有行
我还创建了一个新的实体UserRole.java,如下所示:
@Entity
@Table(name = "user_role")
public class UserRole implements Serializable{
private User user;
private Role role;
@Id
@ManyToOne
@JoinColumn(name = "user_id")
public User getuser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Id
@ManyToOne
@JoinColumn(name = "role_id")
public Role getrole(){
return role;
}
public void setRole(Role role){
this.role = role;
}
}
Run Code Online (Sandbox Code Playgroud)
现在我的问题是:这种结构正确吗?如果是,我如何将现有角色添加到现有用户并在 spring-boot 中获取该用户的角色?
You can find any tutorial connected with many-to-many relationship using Hibernate/Spring Data, example: Spring Data many-to-many
With your model it's simple to add the relationship mappings, like this:
@Entity
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable
private Set<User> users;
}
Run Code Online (Sandbox Code Playgroud)
and this:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String firstname;
private String lastname;
private String username;
private String password;
@ManyToMany(mappedBy = "users")
private Set<Role> roles;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31872 次 |
| 最近记录: |