My First Full Stack Spring Boot / JQuery Application
Part 3 - Creating a Service
Create a Service
@Service
public class PersonService {
private PersonRepository repository;
@Autowired
public PersonService(PersonRepository repository) {
this.repository = repository;
}
public Person create(Person person) {
return repository.save(person);
}
public Person readById(Long id) {
return repository.findById(id).get();
}
public List<Person> readAll() {
Iterable<Person> allPeople = repository.findAll();
List<Person> personList = new ArrayList<>();
allPeople.forEach(personList::add);
return personList;
}
public Person update(Long id, Person newPersonData) {
Person personInDatabase = this.readById(id);
personInDatabase.setFirstName(newPersonData.getFirstName());
personInDatabase.setLastName(newPersonData.getLastName());
personInDatabase.setBirthDate(newPersonData.getBirthDate());
personInDatabase = repository.save(personInDatabase);
return personInDatabase;
}
public Person deleteById(Long id) {
Person personToBeDeleted = this.readById(id);
repository.delete(personToBeDeleted);
return personToBeDeleted;
}
}
constructor
- Set’s the service’s repository
@Autowired
public PersonService(PersonRepository repository) {
this.repository = repository;
}
create
Method
- Adds a new record to the table the service’s repository is accessing.
public Person create(Person person) {
return repository.save(person);
}
readById
Method
- Returns the record with the specified ID from the table the table that the service’s repository is accessing.
public Person readById(Long id) {
return repository.findById(id).get();
}
readAll
Method
- Returns all records from the table the service’s repository is accessing.
public List<Person> readAll() {
Iterable<Person> allPeople = repository.findAll();
List<Person> personList = new ArrayList<>();
allPeople.forEach(personList::add);
return personList;
}
updateById
Method
- Updates the record in the database with the specified
id
with the specifiednewData
public Person update(Long id, Person newPersonData) {
Person personInDatabase = this.readById(id);
personInDatabase.setFirstName(newPersonData.getFirstName());
personInDatabase.setLastName(newPersonData.getLastName());
personInDatabase.setBirthDate(newPersonData.getBirthDate());
personInDatabase = repository.save(personInDatabase);
return personInDatabase;
}
deleteById
Method
- Deletes the record in the database with the specified
id
public Person deleteById(Long id) {
Person personToBeDeleted = this.readById(id);
repository.delete(personToBeDeleted);
return personToBeDeleted;
}