I am making a todo app and whenever I am trying to update an object using put, but each time it is creating a whole new object and storing it.
Here is my Controller:
package com.todo.example.todoexample.controllers;
import com.todo.example.todoexample.models.Task;
import com.todo.example.todoexample.repositories.TaskRepository;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@RestController
public class TaskController {
private TaskRepository taskRepository;
public TaskController(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
@PostMapping(
path = "/create",
consumes = {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE
},
produces = {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE
}
)
public void createTask(@Valid @RequestBody Task task) {
task.setTitle(task.getTitle());
task.setMessage(task.getMessage());
taskRepository.save(task);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteTask(@PathVariable String id) {
taskRepository.deleteById(id);
return ResponseEntity.noContent().build();
}
@RequestMapping("/")
public List<Task> getAllTasks() {
return taskRepository.findAll();
}
/* @PutMapping(
path = "/create/{id}",
consumes = {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE
},
produces = {
MediaType.APPLICATION_XML_VALUE,
MediaType.APPLICATION_JSON_VALUE
}
)
public void updateTask(@PathVariable String id, @Valid @RequestBody Task task) {
taskRepository.findById(id);
task.setTitle(task.getTitle());
task.setMessage(task.getMessage());
taskRepository.save(task);
}*/
}
I have tried to use mongotemplate but it does not really work, I believe this is because I am trying to take in a new object and store it each time. However I am unsure what object to store the task on. As I believe I need to findById, store that variable and then set title and message and then save it! The only problem is, I do not know what object to use. Any help would be great