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
PersonRepository
in theexpert.os.labs.persistence
package - Annotate the interface with
@Repository
using the package fromjakarta.data.repository
to indicate it's a Jakarta Data repository -
Extend the
CrudRepository
interface from the packagejakarta.data.repository
and specify the entity type (Person
) and the ID type (Long
) as type parameters. It defines the basic CRUD operations that can be performed on thePerson
entity
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
AppCassandraRository
in theexpert.os.labs.persistence
package -
Add a main method
-
Set up a try-with-resources block, inside the
main
method, to manage the Jakarta EESeContainer
that is responsible for dependency injection and managing resources -
Create two user instances using the builder of the
Person
class with different data inside thetry
statement -
Obtain an instance of the
PersonRepository
interface 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 thefindById
method where the result is wrapped in anOptional
to 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
AppCassandraRepository
class 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() {
}
}