0% found this document useful (0 votes)
8 views2 pages

Springboot

Spring

Uploaded by

John Jacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Springboot

Spring

Uploaded by

John Jacob
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

Create Entity:

@Entity
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String firstName;


private String lastName;
private int age;

// getters and setters...


}

Create Repository Interface:

public interface PersonRepository extends JpaRepository<Person, Long> {


}

Create Service:

@Service
public class PersonService {
@Autowired
private PersonRepository repository;

public List<Person> getAllPersons() {


return repository.findAll();
}

public Optional<Person> getPersonById(Long id) {


return repository.findById(id);
}

public Person createPerson(Person person) {


return repository.save(person);
}

public Person updatePerson(Long id, Person updatedPerson) {


if (repository.existsById(id)) {
updatedPerson.setId(id);
return repository.save(updatedPerson);
} else {
// Handle error, person not found
return null;
}
}

public void deletePerson(Long id) {


repository.deleteById(id);
}
}
Create Controller:

@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();
}
}

You might also like