@ManyToMany关系在春季启动?

时间:2019-03-19 03:32:00

标签: java hibernate spring-boot

我的“用户”类中有以下一行:

@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);
}

如前所述,我正在努力使用户能够“创建”社区,然后让该用户作为所述新社区的成员出现。当我在上面保存社区时,将其保存在db,并且hibernate为该关系生成了一个表,但是那里没有行。我该如何解决?

0 个答案:

没有答案