I want to create a Post method to update a single property from my API main Object:
@Builder
@Document(collection = "tableItems")
@NoArgsConstructor
@AllArgsConstructor
@Data
public class TableItem {
@Id
private String id;
private int roundNumber;
private RoundState roundState;
private int bigBlind;
private int smallBlind;
private int maxSize;
private int freeSeats;
private double tableChips;
private List<Card> tableCards;
private List<Player> players;
private List<Seat> seats;
}
So, this object ist save on my MongoDB. I want to add a new Player on players, but all other properties should not change!
In my GameController, I have a @RequestMapping("/api/tableitems") and my method looks like this:
@PostMapping("/{id}/players")
public void postNewPlayer(@RequestBody Player newPlayer, String tableId) {
gameService.addNewPlayer(id, newPlayer);
}
In my GameService my addNewPlayer method looks like this:
public void addNewPlayer(Player newPlayer, String tableId) {
TableItem tableToBeUpdated = tableItemsRepo.findById(tableId)
.orElseThrow( () -> new NoSuchElementException(("Table with ID " + tableId + " not found!")));
tableItemsRepo.save(newPlayer);
}
IntelliJ grumbles and throws the following error message:
Inferred type ‘S’ for type parameter ‘S’ is not within its bound; should extend ‘backend.model.TableItem’
And finally my repository looks like this:
@Repository
public interface TableItemsRepository extends MongoRepository<TableItem, String> {
}
Is it at all possible to update a single property of an object with @POST? How does it work? If not, how else can it be done? I am at a loss and would be very grateful for some help… Thanks a lot!
2
Answers
Thanks for the quick feedback! I have seen some thinking errors already... my Repository expects TableItems and I just give it the property I want to change(Player in Players). I also forgot by the @Post the PathVariable with the TableId.
Through your tips I have now found a solution that also works! Here my code:
Controller:
Service:
I did not have to change anything in the repo. The result it looks like this in the DB:
Thank you very much for your help!!
you can have 2 solutions: