BAEL-4842 - Use React and Spring Boot to Build a Simple CRUD App
Initial source module for the article
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package com.baeldung.springbootreact.controller;
|
||||
|
||||
import com.baeldung.springbootreact.domain.Client;
|
||||
import com.baeldung.springbootreact.repository.ClientRepository;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/clients")
|
||||
public class ClientsController {
|
||||
|
||||
private final ClientRepository clientRepository;
|
||||
|
||||
public ClientsController(ClientRepository clientRepository) {
|
||||
this.clientRepository = clientRepository;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List getClients() {
|
||||
return clientRepository.findAll();
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public Client getClient(@PathVariable Long id) {
|
||||
return clientRepository.findById(id).orElseThrow(RuntimeException::new);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ResponseEntity createClient(@RequestBody Client client) throws URISyntaxException {
|
||||
Client savedClient = clientRepository.save(client);
|
||||
return ResponseEntity.created(new URI("/clients/" + savedClient.getId())).body(savedClient);
|
||||
}
|
||||
|
||||
@PutMapping("{id}")
|
||||
public ResponseEntity updateClient(@PathVariable Long id, @RequestBody Client client) {
|
||||
Client currentClient = clientRepository.findById(id).orElseThrow(RuntimeException::new);
|
||||
currentClient.setName(client.getName());
|
||||
currentClient.setEmail(client.getEmail());
|
||||
currentClient = clientRepository.save(client);
|
||||
|
||||
return ResponseEntity.ok(currentClient);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public ResponseEntity deleteClient(@PathVariable Long id) {
|
||||
clientRepository.deleteById(id);
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user