MongoDB - Lab 2
In this lab, you will create a Java application that interacts with a NoSQL database using Jakarta NoSQL and Jakarta EE. The application will define an entity class Book to represent books and use a DocumentTemplate to perform database operations.
1. Define the Book Entity Class
Steps
- Open the
05-documentproject and navigate to thesrc/main/java - Create a
recordcalledBookin theexpert.os.labs.persistencepackage - Define the class with the
@Entityannotation from thejakarta.nosqlpackage - Add the following fields in the record:
@Id String isbn@Column String title@Column int edition@Column int year
Expected results
- Record
Bookcreated
Solution
Click to see...
2. Create the execution class to insert data
Steps
- Create a class called
AppMongoDBin 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 an instance of the
Bookclass with some sample data. You can useUUID.randomUUID().toString()for theisbn, "Effective Java" for the title,1for the edition, and2019for the year. inside thetrystatement -
Obtain a
DocumentTemplateinstance from the packagejakarta.nosql.documentusing the Jakarta SE container by selecting it:container.select(DocumentTemplate.class).get() -
Use the
DocumentTemplateto insert thebookinstance into the NoSQL database -
Printout the content of the book inserted
-
Use the
DocumentTemplateto perform a query to retrieve a book by its title -
Printout the result
-
Define a private constructor for the
AppMongoDBclass 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 jakarta.nosql.document.DocumentTemplate;
import java.util.Optional;
import java.util.UUID;
public class AppMongoDb {
public static void main(String[] args) {
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
Book book = new Book(UUID.randomUUID().toString(), "Effective Java", 1, 2019);
DocumentTemplate template = container.select(DocumentTemplate.class).get();
Book saved = template.insert(book);
System.out.println("Book saved: = " + saved);
Optional<Book> bookFound = template.select(Book.class).where("title").eq("Effective Java").singleResult();
System.out.println("Book Found = " + bookFound);
}
}
private AppMongoDb() {
}
}