Springboot
Springboot
@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
Create Service:
@Service
public class PersonService {
@Autowired
private PersonRepository repository;
@RestController
@RequestMapping("/api/persons")
public class PersonController {
@Autowired
private PersonService personService;
@GetMapping
public List<Person> getAllPersons() {
return personService.getAllPersons();
}
@GetMapping("/{id}")
public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
Optional<Person> person = personService.getPersonById(id);
return person.map(ResponseEntity::ok)
.orElseGet(() -> ResponseEntity.notFound().build());
}
@PostMapping
public ResponseEntity<Person> createPerson(@RequestBody Person person) {
Person createdPerson = personService.createPerson(person);
return ResponseEntity.status(HttpStatus.CREATED).body(createdPerson);
}
@PutMapping("/{id}")
public ResponseEntity<Person> updatePerson(@PathVariable Long id, @RequestBody
Person updatedPerson) {
Person updated = personService.updatePerson(id, updatedPerson);
return updated != null ? ResponseEntity.ok(updated) :
ResponseEntity.notFound().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deletePerson(@PathVariable Long id) {
personService.deletePerson(id);
return ResponseEntity.noContent().build();
}
}