java postMaprest API spring Boot 无法获取id

nlejzf6q  于 2023-01-07  发布在  Java
关注(0)|答案(1)|浏览(162)

我正在学习,到目前为止,我创建了多对多双向数据库-用户可以创建许多组,组可以有许多用户-我找不到我的GroupsController PostMap工作的方法,从我的理解,它需要首先获得用户ID,以便在组的连接表中设置正确的关系,因为只有当用户创建/加入组时才应该设置关系,当用户创建注册程序时没有。 Postman 抛出500和intelliJ:

Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "com.ilze.highlight.entity.Groups.getId()" is null] with root cause

java.lang.NullPointerException: Cannot invoke "java.lang.Long.longValue()" because the return value of "com.ilze.highlight.entity.Groups.getId()" is null

我使用lombok - @Data,@Getter,因此getId()应该可以从Group类中使用。当用户决定创建一个新组时,我的GroupsController与POSTMap:

@RestController
@RequestMapping("api/groups") // pre-path
public class GroupsController{

  @Autowired
  private GroupsService groupsService;

  @Autowired
  private UserService userService;

  @Autowired
  private final GroupsRepository groupsRepository;

  @Autowired
  private UserRepository userRepository;

  public GroupsController(GroupsRepository groupsRepository) {
    this.groupsRepository = groupsRepository;
  }

  @GetMapping("/all-groups")
  public List<Groups> getGroups(){
    return (List<Groups>) groupsRepository.findAll();
  }

  @PostMapping("/user/{usersId}/create-group")
  public ResponseEntity<Groups> createGroup(@PathVariable(value = "usersId") Long usersId, @RequestBody Groups groupRequest){
    Groups group = userRepository.findById(usersId).map(users -> {
      long groupsId = groupRequest.getId();

      // add and create new group
      users.addGroup(groupRequest);
      return groupsRepository.save(groupRequest);
    }).orElseThrow(() -> new ResourceNotFoundException("Not found user with id = " + usersId));

    return new ResponseEntity<>(group, HttpStatus.CREATED);
  }
}

组数据库类:

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Table(name = "group_collection")
public class Groups {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  @Column(name ="group_name", unique = true, nullable = false, length = 20)
  private String groupName;

  @Column(name = "size", nullable = false)
  private int size;

  @Column(name = "strict", nullable = false)
  private boolean strict;

  @Column(name = "open", nullable = false)
  private boolean open;

  @Column(name ="description", length = 300)
  private String description;

  @Column(name = "create_time", nullable = false)
  private LocalDateTime createTime;

  @ManyToMany(fetch = FetchType.LAZY,
  cascade = {
    CascadeType.PERSIST,
    CascadeType.MERGE,
    CascadeType.DETACH,
    CascadeType.REFRESH
  },
  mappedBy = "groups")
  @JsonIgnore
  private Set<User> users = new HashSet<>();

  public Set<User> getUsers() {
    return users;
  }

  public void setUsers(Set<User> users) {
    this.users = users;
  }

}

和数据库的用户类:

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "users")
public class User {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "id")
  private Long id;

  @Column(name = "username", unique = true, nullable = false, length = 100)
  private String username;

  @Column(name = "password", nullable = false)
  private String password;

  @Column(name = "email", nullable = false)
  private String email;

  @Column(name = "create_time", nullable = false)
  private LocalDateTime createTime;

  @Enumerated(EnumType.STRING)
  @Column(name = "role", nullable = false)
  private Role role;

  @Transient
  private String accessToken;

  @Transient
  private String refreshToken;

  @ManyToMany(fetch = FetchType.LAZY,
    cascade = {
      CascadeType.PERSIST,
      CascadeType.MERGE,
      CascadeType.DETACH,
      CascadeType.REFRESH
    })
  @JoinTable(name = "groups_x_user",
    joinColumns = { @JoinColumn(name = "users_id") },
    inverseJoinColumns = {@JoinColumn(name = "groups_id")})
  private Set<Groups> groups = new HashSet<>();

  public void addGroup(Groups group) {
    this.groups.add(group);
    group.getUsers().add(this);
  }

  public void removeGroup(long id){
    Groups group = this.groups.stream().filter(g ->
      g.getId() == id).findFirst().orElse(null);
    if(group != null){
      this.groups.remove(group);
      group.getUsers().remove(this);
    }
  }

作为参考,我的GroupsService实现:

@Service
public class GroupsServiceImpl implements GroupsService{

  private final GroupsRepository groupsRepository;

  public GroupsServiceImpl(GroupsRepository groupsRepository) {
    this.groupsRepository = groupsRepository;
  }

  @Override
  public Groups saveGroup(Groups group) {
    group.setCreateTime(LocalDateTime.now());
    return groupsRepository.save(group);
  }

  @Override
  public Optional<Groups> findByGroupName(String groupName) {
    return groupsRepository.findByGroupName(groupName);
  }

}
vhmi4jdf

vhmi4jdf1#

您需要持久化请求中的对象。由于您具有多对多关系,因此您可以从两端插入相关对象。在您的示例中:只需将现有用户添加到新创建的组
这个方法看起来像这样:

@PostMapping("/user/{usersId}/groups")
public ResponseEntity<Groups> createGroup(@PathVariable(value = "usersId") Long usersId, @RequestBody Groups groupRequest) {
     Groups createdGroup = userRepository.findById(usersId)
     .map(user -> {
          groupRequest.setId(null); // ID for new entry will be generated by entity framework, prevent override from outside
          groupRequest.getUsers().add(user); // add relation
          return groupsRepository.save(groupRequest);
    }).orElseThrow(() -> new ResourceNotFoundException("Not found user with id = " + usersId));

    return new ResponseEntity<>(createdGroup, HttpStatus.CREATED);
}

相关问题