英文:
many-to-many relationship springboot mysql
问题
我有两个模型:User(用户)和Role(角色),它们之间是多对多的关系。
我需要添加一个用户并为他分配数据库中已有的特定角色。
------User------
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_Id")
private int userId;
@Column(name = "name")
private String name;
@Column(name = "lastname")
private String lastname;
@Column(name = "email")
private String email;
@Column(name = "password")
private String password;
@Column(name = "isActive")
private boolean isActive;
@Column(name = "lastActive")
private String lastActive;
@Column(name = "createdDate")
private String createdDate;
@Column(name = "isBlocked")
private boolean isBlocked;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "institution_id", nullable = false)
@JsonIgnoreProperties(value = {"user"})
private Institution institution;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH})
@JoinTable(name = "user_has_role",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "user_id",
nullable = false, updatable = true)},
inverseJoinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "role_id",
nullable = false, updatable = true)})
@JsonIgnoreProperties(value = {"users"})
private Set<Role> roles = new HashSet<>();
}
--------Roles--------
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_Id")
private int roleId;
@Column(name = "name")
private String name;
@Column(name = "description")
private String description;
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = {"roles"})
private Set<User> users = new HashSet<>();
}
// Application Controller
@PostMapping("/addUser")
public String addUser(@RequestBody User user) {
userrepository.save(user);
return "user saved with name: " + user.getName();
}
// JSON请求体
{
"userId" : 7,
"name": "test",
"lastname": "testlast",
"email": "testtest@yahoo.com",
"password": "test123",
"lastActive": "04/05/21",
"createdDate": "02/04/20",
"institution": {
"institutionId": 4
},
"roles": [
{
"roleId": 2
}
],
"isActive": false,
"isBlocked": true
}
一切都正常运行,用户-角色表会添加一条记录,其中userId为7,roleId为2。但问题是角色表被更新,字段name和description的值被清空并替换为null值。请问有什么解决方法吗?
英文:
i have 2 models User and roles , its a many to many relation ship.
i need to add a user and give him a specific role already present in my data base.
------User------
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="user_Id")
private int userId;
@Column(name="name")
private String name;
@Column(name="lastname")
private String lastname;
@Column(name="email")
private String email;
@Column(name="password")
private String password;
@Column(name="isActive")
private boolean isActive;
@Column(name="lastActive")
private String lastActive;
@Column(name="createdDate")
private String createdDate;
@Column(name="isBlocked")
private boolean isBlocked;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "institution_id", nullable = false)
@JsonIgnoreProperties(value = {"user"})
private Institution institution;
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.DETACH,CascadeType.MERGE,CascadeType.REFRESH})
@JoinTable(name = "user_has_role",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "user_id",
nullable = false, updatable = true)},
inverseJoinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "role_id",
nullable = false, updatable = true)})
@JsonIgnoreProperties(value = {"users"})
private Set<Role> roles = new HashSet<>();
}
--------Roles--------
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Entity
@Table(name = "role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="role_Id")
private int roleId;
@Column(name="name")
private String name;
@Column(name="description")
private String description;
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
@JsonIgnoreProperties(value = {"roles"})
private Set<User> users = new HashSet<>();
}
and the application's controller
@PostMapping("/addUser")
public String addUser(@RequestBody User user) {
userrepository.save(user);
return "user saved with name: " + user.getName();
}
and this is the json body i send with the api request.
{
"userId" : 7,
"name": "test",
"lastname": "testlast",
"email": "testtest@yahoo.com",
"password": "test123",
"lastActive": "04/05/21",
"createdDate": "02/04/20",
"institution": {
"institutionId": 4
},
"roles": [
{
"roleId": 2
}
],
"active": false,
"blocked": true
}
everything worls just fine to my user-has-role table a record is added with the userId = 7 and roleId=2
but the problem is that the table role is getting updated and the fields name and description are getting erased and replaced by null values...
any ideas please
答案1
得分: 1
您已将CascadeType.PERSIST
添加到User
和Role
的@ManyToMany
关联中。<br>
当将User
实体持久化到实体管理器时,它还将持久化Role
实体。由于您在请求负载中传递了Role
的主键,它将创建/更新Role表格。
您需要从关联中移除CascadeType.PERSIST
,它将按预期工作。
英文:
You have added CascadeType.PERSIST
to User
and Role
@ManyToMany
join.<br>
When the User
entity is persisted to the EntityManager, it will also persist the Role
entity. As you are passing the primary key in the request payload for Role
it will create/update the Role table.
You need to remove the CascadeType.PERSIST
from joining and it will work as expected.
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.REFRESH })
@JoinTable(name = "user_has_role",
joinColumns = {
@JoinColumn(name = "user_id", referencedColumnName = "user_id",
nullable = false, updatable = true)},
inverseJoinColumns = {
@JoinColumn(name = "role_id", referencedColumnName = "role_id",
nullable = false, updatable = true)})
@JsonIgnoreProperties(value = {"users"})
private Set<Role> roles = new HashSet<>();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论