首页 > 解决方案 > 春季启动中的@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);
}

如前所述,我试图让用户可以“创建”一个社区,然后让该用户作为所述新社区的成员出现......当我保存上面的社区时,它被保存在数据库中,并且休眠状态为该关系生成了一个表,但是那里没有行。我该如何解决?

标签: javahibernatespring-boot

解决方案


推荐阅读