Databases Reference
In-Depth Information
Read
Our application has two views that present contact information: the first one shows a
list of contacts and the second one shows the information of a single contact.
First, we have to implement a method that fetches all the contacts from Redis. We
can implement the
findAll()
method by following these steps:
1.
Fetch all the contacts from the contact set.
2.
Create a new
ArrayList
object and return the created object.
The source code of the
findAll()
method is given as follows:
@Override
public List<Contact> findAll() {
Collection<Contact> contacts = redisTemplate.opsForSet().
members("contacts");
return new ArrayList<Contact>(contacts);
}
Second, we have to implement a method that returns the information of a single
contact. Our implementation of the
findById()
method includes the following steps:
1.
Create the key of the contact.
2.
Get the
Contact
object from Redis.
3.
If no contact is found, throw
NotFoundException
.
4.
Return the found object.
The source code of the
findById()
method is given as follows:
@Override
public Contact findById(Long id) throws NotFoundException {
String key = buildKey(id);
Contact found = redisTemplate.opsForValue().get(key);
if (found == null) {
throw new NotFoundException("No contact found with id: {}" +
id);
}
return found;
}