I am trying to build a very small REST API with a mysql database. I am using Spring boot and Tomcat to deploy it locally. One of the services I am working on is to retrieve messages from the database. I have the ability to get ALL the messages created from the database, and I have the ability to filter based on ID but I want to be able to filter based on other parameters as well. The other parameters are called "messageCreated" and "messageSubscribed" they're both int parameters.
Here is my Controller class:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.NoSuchElementException;
@RestController
@RequestMapping("/messages")
public class MessageController {
@Autowired
MessageService messageService;
@GetMapping("")
public List<Message> list() {
return messageService.listAllMessage();
}
@GetMapping(value ={"/id"})
public ResponseEntity<Message> get(@PathVariable Integer id) {
try {
Message message = messageService.getMessage(id);
return new ResponseEntity<Message>(message, HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<Message>(HttpStatus.NOT_FOUND);
}
}
@PostMapping("/")
public void add(@RequestBody Message message) {
messageService.saveMessage(message);
}
@PutMapping("/{id}")
public ResponseEntity<?> update(@RequestBody Message message, @PathVariable Integer id) {
try {
Message existMessage = messageService.getMessage(id);
message.setId(id);
messageService.saveMessage(message);
return new ResponseEntity<>(HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Integer id) {
messageService.deleteMessage(id);
}
}