0% found this document useful (0 votes)
22 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)
22 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

Create Entity:

@Entity
public class Person {
@Id
@GeneratedValue(strategy = [Link])
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 [Link]();
}

public Optional<Person> getPersonById(Long id) {


return [Link](id);
}

public Person createPerson(Person person) {


return [Link](person);
}

public Person updatePerson(Long id, Person updatedPerson) {


if ([Link](id)) {
[Link](id);
return [Link](updatedPerson);
} else {
// Handle error, person not found
return null;
}
}

public void deletePerson(Long id) {


[Link](id);
}
}
Create Controller:

@RestController
@RequestMapping("/api/persons")
public class PersonController {
@Autowired
private PersonService personService;

@GetMapping
public List<Person> getAllPersons() {
return [Link]();
}

@GetMapping("/{id}")
public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
Optional<Person> person = [Link](id);
return [Link](ResponseEntity::ok)
.orElseGet(() -> [Link]().build());
}

@PostMapping
public ResponseEntity<Person> createPerson(@RequestBody Person person) {
Person createdPerson = [Link](person);
return [Link]([Link]).body(createdPerson);
}

@PutMapping("/{id}")
public ResponseEntity<Person> updatePerson(@PathVariable Long id, @RequestBody
Person updatedPerson) {
Person updated = [Link](id, updatedPerson);
return updated != null ? [Link](updated) :
[Link]().build();
}

@DeleteMapping("/{id}")
public ResponseEntity<Void> deletePerson(@PathVariable Long id) {
[Link](id);
return [Link]().build();
}
}

You might also like