问题描述
我的Spring-Boot应用程序中有两个实体:
I have two Entities in my Spring-Boot Application:
User.java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String firstname;
String lastname;
String username;
String password;
}
和
Role.java
Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Long id;
String name;
String description;
}
用于MySql数据库
我已经排除了此问题的getter和setter方法.
I have excluded the getter and setter methods for this question.
我想实现两个实体之间的多对多关系.每个用户都应该能够为自己分配多个角色
I want to realise a Many-to-Many-Relationship between both Entities. Every user should be able to assign multiple roles to himself
我已经为数据库中的两个表创建了一个映射表.它有行
I already Created a mapping table for both tables in my database. It has the rows
- user_id
- role_id.
我还创建了一个新的 UserRole.java 实体,如下所示:
I also created a new Entity UserRole.java which looks like this:
@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;
}
}
现在我的问题是:这种结构正确吗?如果是,我如何在现有用户中添加现有角色并在春季启动中获得该用户的角色?
Now my question: is this construction correct? If yes, how do i add existing roles to an existing user and get the roles of this user in spring-boot?
推荐答案
您可以使用Hibernate/Spring Data查找与多对多关系相关的任何教程,例如: Spring数据很多对多
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;
}
和这个:
@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;
}
这篇关于春季启动时两个实体之间的多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!