簡體   English   中英

發布映射 rest api spring 引導無法獲取 id

[英]post mapping rest api spring boot cannot get id

我在學習,到目前為止,我創建了多對多雙向數據庫——用戶可以創建很多組,組可以有很多用戶——我找不到讓我的 GroupsController Post 映射工作的方法,據我所知,它需要首先獲得用戶id,以便在組的加入表中設置正確的關系,因為只有在用戶創建/加入組時才應該設置關系,而不是在用戶創建注冊過程時設置。 Postman 拋出 500 和智能:

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() 應該可以從組 class 中使用。當用戶決定創建新組時,我的 GroupsController 帶有 POST 映射:

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

集團數據庫class:

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

}

數據庫用戶 class:

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

}

您需要保留請求中的 object。 並且由於您具有多對多關系,因此您可以從兩側插入相關的 object。 在您的情況下:只需將現有用戶添加到新創建的組

該方法看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM