MongoDB - Lab 4
In this lab, you will create Java classes that model an Author entity along with related classes for building Author objects, representing addresses, and describing jobs. These classes will be used to interact with a NoSQL database using Jakarta NoSQL and Jakarta EE. Below are the step-by-step instructions for creating these classes
1. Define the Address Embeddable Class
Steps
- Create a class called
Addressin theexpert.os.labs.persistencepackage - Annotate it using the
@Embeddablefrom theorg.eclipse.jnosql.mappingpackage -
Add two attributes:
cityandstreetand use the@Columnannotation, both asString -
Implement constructors, getter methods,
equals,hashCode, andtoStringmethods
Solution
Click to see...
import jakarta.nosql.Column;
import org.eclipse.jnosql.mapping.Embeddable;
@Embeddable
public class Address {
@Column
private String street;
@Column
private String city;
public Address() {
}
public Address(String street, String city) {
this.street = street;
this.city = city;
}
// other method ignored
}
2. Define the Job Embeddable Class
Steps
- Create a class called
Jobin theexpert.os.labs.persistencepackage - Annotate it using the
@Embeddablefrom theorg.eclipse.jnosql.mappingpackage -
Add two attibutes:
salaryandoccupationand use the@Columnannotation, wheresalaryis adoubleandoccupationaString -
Implement constructors, getter methods,
equals,hashCode, andtoStringmethods
Solution
Click to see...
import jakarta.nosql.Column;
import org.eclipse.jnosql.mapping.Embeddable;
@Embeddable
public class Job {
@Column
private double salary;
@Column
private String occupation;
public Job() {
}
public Job(double salary, String occupation) {
this.salary = salary;
this.occupation = occupation;
}
// other method ignored
}
3. Define the Author Entity Class
Steps
- Create a class called
Authorin theexpert.os.labs.persistencepackage - Define the class with the
@Entityannotation from thejakarta.nosqlpackage -
Add the following fields in in the record:
Annotation Type Name @IdLongid@ColumStringname@ColumList<String>phones@ColumAddressaddress@ColumJobjob -
Implement constructors, getter methods,
equals,hashCode, andtoStringmethods
Solution
Click to see...
import jakarta.nosql.Column;
import jakarta.nosql.Entity;
import jakarta.nosql.Id;
import java.util.List;
@Entity
public class Author {
@Id
private Long id;
@Column
private String name;
@Column
private List<String> phones;
@Column
private Address address;
@Column
private Job job;
public Author() {
}
public Author(Long id, String name, List<String> phones, Address address, Job job) {
this.id = id;
this.name = name;
this.phones = phones;
this.address = address;
this.job = job;
}
// other method ignored
}
4. Implement the Builder class
Steps
- Create a class called
AuthorBuilderin theexpert.os.labs.persistencepackage -
Add the same fields we had previously added to the
Authorclass, without the annotations -
Add the builder methods for each field
- Add the
build()method creating a new instance ofAuthorusing its constructor - In the
Authorclass add the builder method referring to theAuthorBuilder
Solution
Click to see...
import java.util.List;
public class AuthorBuilder {
private long id;
private String name;
private List<String> phones;
private Address address;
private Job job;
public AuthorBuilder id(long id) {
this.id = id;
return this;
}
public AuthorBuilder name(String name) {
this.name = name;
return this;
}
public AuthorBuilder phones(List<String> phones) {
this.phones = phones;
return this;
}
public AuthorBuilder address(Address address) {
this.address = address;
return this;
}
public AuthorBuilder job(Job job) {
this.job = job;
return this;
}
public Author build() {
return new Author(id, name, phones, address, job);
}
}
5. Create the execution class
Steps
- Create a class called
AppMongoDBSubdocumentsin theexpert.os.labs.persistencepackage -
Add a main method
-
Create a
ThreadLocalRandominstance and get the next value, associating it to an attribute -
Set up a try-with-resources block, inside the
mainmethod, to manage the Jakarta EESeContainerthat is responsible for dependency injection and managing resources -
Create a new instance of
Faker -
Create a new instance of the
Authorclass usingfakerto provide data -
Create a new instance of the
Jobclass usingfakerto provide data -
Create a new instance of the
Authorclass usingfakerto provide data -
Obtain a
DocumentTemplateinstance fromjakarta.nosql.documentpackage by selecting it:container.select(DocumentTemplate.class).get() -
Use the
DocumentTemplateto insert theAuthorinstance into the NoSQL database and retrieve the saved author -
Printout the saved author
-
Use the
DocumentTemplateto perform a query to retrieve authors by the city in their address -
Printout the result
-
Define a private constructor for the
AppCassandraOperationsclass to prevent instantiation since it contains only static methods: -
Run the
main()method
Expected results
-
The following output
Author saved = Author{id=-5926041563979906242, name='Marissa Koch Jr.', phones=[347-971-6761, 1-199-518-8887], address=Address{street='Roselee Ports', city='Stantonport'}, job=Job{salary=12.12, occupation='Legal Assistant'}} Entities found: [Author{id=-5926041563979906242, name='Marissa Koch Jr.', phones=[347-971-6761, 1-199-518-8887], address=Address{street='Roselee Ports', city='Stantonport'}, job=Job{salary=12.12, occupation='Legal Assistant'}}]
Solution
Click to see...
import com.github.javafaker.Faker;
import jakarta.enterprise.inject.se.SeContainer;
import jakarta.enterprise.inject.se.SeContainerInitializer;
import jakarta.nosql.document.DocumentTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class AppMongoDBSubdocuments {
public static void main(String[] args) {
ThreadLocalRandom random = ThreadLocalRandom.current();
long id = random.nextLong();
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
Faker faker = new Faker();
Address address = new Address(faker.address().streetName(), faker.address().city());
Job job = new Job(12.12, faker.job().title());
Author author = Author.builder()
.phones(Arrays.asList(faker.phoneNumber().cellPhone(), faker.phoneNumber().cellPhone()))
.name(faker.name().fullName()).address(address).job(job).id(id).build();
DocumentTemplate template = container.select(DocumentTemplate.class).get();
Author saved = template.insert(author);
System.out.println("Author saved = " + saved);
List<Author> people = template.select(Author.class).where("address.city").eq(address.getCity()).result();
System.out.println("Entities found: " + people);
}
}
private AppMongoDBSubdocuments() {
}
}