Cassandra - Lab 3
In this lab, we will learn how to use Repository with Eclipse JNoSQL.
1. Define the Repository interface
Steps
- Create an interface called
PersonRepositoryin theexpert.os.labs.persistencepackage - Annotate the interface with
@Repositoryusing the package fromjakarta.data.repositoryto indicate it's a Jakarta Data repository -
Extend the
CrudRepositoryinterface from the packagejakarta.data.repositoryand specify the entity type (Person) and the ID type (Long) as type parameters. It defines the basic CRUD operations that can be performed on thePersonentity
Expected results
- A repository class ready to perform database operations
Solution
Click to see...
2. Create the execution class for Cassandra Repository
Steps
- Create a class called
AppCassandraRositoryin theexpert.os.labs.persistencepackage -
Add a main method
-
Set up a try-with-resources block, inside the
mainmethod, to manage the Jakarta EESeContainerthat is responsible for dependency injection and managing resources -
Create two user instances using the builder of the
Personclass with different data inside thetrystatement -
Obtain an instance of the
PersonRepositoryinterface using Jakarta EE'sSeContainer. It is done by selecting and getting an instance of the repository -
Save the user
-
Retrieve data from the repository by
id(1L) using thefindByIdmethod where the result is wrapped in anOptionalto handle the possibility of a non-existent entity -
Print the retrieved entity or indicate if it was not found
-
Define a private constructor for the
AppCassandraRepositoryclass to prevent instantiation since it contains only static methods: -
Run the
main()method
Expected results
-
The following output
Solution
Click to see...
import jakarta.enterprise.inject.se.SeContainer;
import jakarta.enterprise.inject.se.SeContainerInitializer;
import java.util.Map;
import java.util.Optional;
public class AppCassandraRepository {
public static void main(String[] args) {
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
Person user1 = Person.builder()
.contacts(Map.of("twitter", "otaviojava", "linkedin", "otaviojava","youtube", "otaviojava"))
.name("Otavio Santana").id(1).build();
PersonRepository repository = container.select(PersonRepository.class).get();
repository.save(user1);
Optional<Person> person = repository.findById(1L);
System.out.println("Entity found: " + person);
}
}
private AppCassandraRepository() {
}
}