spring-boot - Spring boot JPA - 使用Controller中的额外列更新ManyToMany关系的中间表的最佳解决方案是什么?
问题描述
我在我的项目中使用 Spring Boot 作为后端。在数据库(MySQL)中,我有一个多对多关系,其中包含下一个实体:用户、兴趣和 relUserInterest。RelUserInterest 是 User 和 Interest 之间的中间表,并且有额外的列。
用户实体
@Entity
public class User {
@Id @GeneratedValue private Long id;
@NotNull
@Column (unique = true) private String email;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@NotNull
Set<RelUserInterest> priority = new HashSet<>();
// more attributes, constructor, get and set
}
利益实体
@Entity
public class Interest {
@Id
@GeneratedValue
private long id;
@NotEmpty
@Column(unique = true)
private String nameInterest;
@OneToMany(mappedBy = "interest", cascade = CascadeType.ALL)
@NotNull
Set<RelUserInterest> priority = new HashSet<>();
// more attributes, constructor, get and set
}
RelUserInterest 实体
@Entity
@Table(name = "rel_user_interest")
@IdClass(UserInterestId.class)
public class RelUserInterest implements Serializable {
@Id
@ManyToOne
@JoinColumn(name = "user_id", referencedColumnName = "id")
User user;
@Id
@ManyToOne
@JoinColumn(name = "interest_id", referencedColumnName = "id")
Interest interest;
int priority;
// constructor, get and set
}
到目前为止,一切都很好。我想更新用户和他们的兴趣。我的控制器是这个。我想做的是当我更新现有用户时,更新中间表(RelUserInterest)。
@PutMapping("/update/{id}")
public ResponseEntity<?> updateUser(@Validated @RequestBody UserDTOUpdate userDTOUpdate, BindingResult result, @PathVariable Long id) {
// More code
User user = usersService.getUserById(id);
// Code updating other attributes
// Here this the problem --> I don't know how to update the attribute priority of RelUserInterest
usersService.updateUser(user);
return new ResponseEntity<>(new Mensaje("Usuario actualizado"), HttpStatus.CREATED);
}
我找到了几个链接,但我不确定哪个是最好的解决方案,我不知道如何使用我的代码。
在邮递员中,我想发送下一个 JSON,尽管如果解决方案有必要,兴趣数组可能会有所不同:
{
"age": 22,
"genre": "Male",
"userName": "Miguel",
"roles": [
"ROLE_ADMIN",
"ROLE_USER"
],
"interest": [
{
"interestID": 1,
"nameInterest": "Museum",
"priority": 9
}
]
}
问题
那么,问题来了:如何更新 RelUserEntity 表的属性优先级?我认为制作中间表存储库是一个错误。我有点失落。我希望你能帮助我。谢谢你。
解决方案
推荐阅读
- blockchain - Solidity - “编译器错误:堆栈太深”
- javascript - 除非第一次警告,否则 Jquery 在单击后找不到任何元素
- pandas - 查找关于熊猫数据框中某个特征的行的第一次出现
- r - 在R中计算分类变量的组合,无论顺序如何?
- javascript - loadStripe 不断给我 {type: "invalid_request_error", message: "Invalid API Key provided: undefined"} 错误
- react-native - 从 CI/CD gitlab 发布时如何使用访问令牌进行博览会
- python-3.x - 附加和更新字典创建克隆
- python - 如何从另一个脚本访问函数的特定变量?
- php - Laravel Voyager 图片上传失败并收到错误消息“Intervention\Image\Exception\NotSupportedException Reading Exif data is not supported”
- c++ - gRPC 客户端不返回证书