Databases Reference
In-Depth Information
Contact contact = Contact.getBuilder(added.getFirstName(), added.
getLastName())
.address(added.getStreetAddress(), added.getPostCode(),
added.getPostOffice(), added.getState(), added.getCountry())
.emailAddress(added.getEmailAddress())
.phoneNumber(added.getPhoneNumber())
.build();
return repository.save(contact);
}
Read
Our application has to provide a list of all contacts and the information of a single
contact to its user. The
ContactService
interface declares two methods, which are
relevant to these use cases. These methods are:
findAll()
and
findById()
.
Our implementation of the
findAll()
method is fairly simple. We simply delegate
the method call forward to the repository. The source code of the
findAll()
method
is given as follows:
@Transactional(readOnly = true)
@Override
public List<Contact> findAll() {
return repository.findAll();
}
Now we have to create an implementation of the
findById()
method. Our
implementation contains the following steps:
1.
Find the contact by calling our repository's
findOne()
method.
2.
If no contact is found, throw a
NotFoundException
.
3.
Return the found contact.
The source code of the
findById()
method is given as follows:
@Transactional(readOnly = true)
@Override
public Contact findById(Long id) throws NotFoundException {
Contact found = repository.findOne(id);
if (found == null) {
throw new NotFoundException("No contact found with id: " +
id);