Search code examples
javamongodbspring-bootintellij-ideahttp-post

How to update a single Property of an Object in Database with Post and NOT PATCH? (Java, springboot)


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!


Solution

  • you can have 2 solutions: