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
@Autowired
public PersonService(PersonRepository repository) {
    this.repository = repository;
}

create Method
public Person create(Person person) {
    return repository.save(person);
}

readById Method
public Person readById(Long id) {
    return repository.findById(id).get();
}

readAll Method
public List<Person> readAll() {
    Iterable<Person> allPeople = repository.findAll();
    List<Person> personList = new ArrayList<>();
    allPeople.forEach(personList::add);
    return personList;
}

updateById Method
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
public Person deleteById(Long id) {
    Person personToBeDeleted = this.readById(id);
    repository.delete(personToBeDeleted);
    return personToBeDeleted;
}