java - 春季启动中的@ManyToMany关系?
问题描述
我的“用户”类中有以下行:
@ManyToMany(mappedBy = "members")
private List<Community> communities = new ArrayList<>();
我在“社区”类中有以下行:
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable
private List<User> members;
我正在努力让用户可以“创建”一个社区,然后让该用户作为所述新社区的成员出现。
这是我创建社区的代码...
public ResponseEntity<?> newCommunity(@Valid @RequestBody NewCommunityRequestPayload newCommunityrequest) {
// Get current user.
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
// New list of users here, since it is a new community.
List<User> members = new ArrayList<>();
User currentUser;
if (principal instanceof User){
currentUser = ((User)principal);
// Add this user to the member list.
members.add(currentUser);
// create a new Community object.
Community newCommunity = new Community();
// Set the name, and set the member list.
newCommunity.setCommunityName(newCommunityRequest.getCommunityName());
newCommunity.setMembers(members);
Community result = communityRepository.save(newCommunity);
return new ResponseEntity(new ApiResponse(true, "Created new community."),
HttpStatus.CREATED);
}
return new ResponseEntity(new ApiResponse(false, "Invalid user object"),
HttpStatus.BAD_REQUEST);
}
如前所述,我试图让用户可以“创建”一个社区,然后让该用户作为所述新社区的成员出现......当我保存上面的社区时,它被保存在数据库中,并且休眠状态为该关系生成了一个表,但是那里没有行。我该如何解决?
解决方案
推荐阅读
- java - 在 Spring Boot 应用程序中调用存储过程并将结果分配给 RowMapper
- excel - 输入框阻止用户在值为空白时按 Enter
- asp.net-core - Blazor Server / Asp.Net Core:在 IIS 上发布时,Http 请求不会将用户身份传递给 MVC 控制器
- visual-studio-code - 为什么我的 VS Code 终端不断被终止?
- django - Django中自定义格式的唯一ID生成器
- node.js - discord.js 获取用户集成
- bots - 如何让我的不和谐机器人阅读其他机器人嵌入消息
- html - 无法从 mat-chip 中删除悬停背景颜色
- styleframe - StyleFrame(或 styleframe?)导入问题
- c - 二进制数:+ 和 | 之间的奇怪差异