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-document
project and navigate to thesrc/main/java
- Create a
record
calledBook
in theexpert.os.labs.persistence
package - Define the class with the
@Entity
annotation from thejakarta.nosql
package - Add the following fields in the record:
@Id String isbn
@Column String title
@Column int edition
@Column int year
Expected results
- Record
Book
created
Solution
Click to see...
2. Create the execution class to insert data
Steps
- Create a class called
AppMongoDB
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 an instance of the
Book
class with some sample data. You can useUUID.randomUUID().toString()
for theisbn
, "Effective Java" for the title,1
for the edition, and2019
for the year. inside thetry
statement -
Obtain a
DocumentTemplate
instance from the packagejakarta.nosql.document
using the Jakarta SE container by selecting it:container.select(DocumentTemplate.class).get()
-
Use the
DocumentTemplate
to insert thebook
instance into the NoSQL database -
Printout the content of the book inserted
-
Use the
DocumentTemplate
to perform a query to retrieve a book by its title -
Printout the result
-
Define a private constructor for the
AppMongoDB
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 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() {
}
}