Handling Embedded Data in NoSQL With Java
Handle embedded data in NoSQL with Java using Jakarta NoSQL. Compare flat vs. grouped structures using @Embeddable to optimize document storage and querying in MongoDB.
Join the DZone community and get the full member experience.
Join For FreeNoSQL databases differ from relational databases by allowing more complex structures without requiring traditional relationships such as one-to-many or one-to-one. Instead, NoSQL databases leverage flexible types, such as arrays or subdocuments, to store related data efficiently within a single document. This flexibility enables developers to design models that suit their application's querying and performance needs.
Jakarta NoSQL is a Java framework that simplifies interactions with NoSQL databases, including MongoDB. It provides annotations that determine how data is mapped and stored, allowing developers to control whether embedded objects are grouped or stored in a flat manner.
When working with MongoDB and Jakarta NoSQL, one of the key considerations is how to structure your documents. Choosing between a flat structure and a grouped structure impacts how the data is stored, queried, and retrieved. In this article, we explore these two approaches using a practical example.
Jakarta NoSQL and Product Entity
To understand the flat and grouped structures, let's first introduce the Product
entity and see how Jakarta NoSQL annotations work:
@Entity
public class Product {
@Id
@Convert(ObjectIdConverter.class)
private String id;
@Column
private String name;
@Column
private Manufacturer manufacturer;
@Column
private List<String> tags;
@Column
private Set<Category> categories;
Product(String name, Manufacturer manufacturer, List<String> tags, Set<Category> categories) {
this.name = name;
this.manufacturer = manufacturer;
this.tags = tags;
this.categories = categories;
}
public static ProductBuilder builder() {
return new ProductBuilder();
}
}
Now, let's explore how the manufacturer
field can be stored differently based on Jakarta NoSQL annotations.
Understanding Grouped and Flat Structures
Grouped Structure
A grouped structure organizes related information into distinct objects within the document. This approach improves readability and allows for a cleaner domain modeling practice. Jakarta NoSQL achieves this by using. @Embeddable(Embeddable.EmbeddableType.GROUPING)
.
Example:
{
"_id": { "$oid": "67b264520abd020ec0eb9a4c" },
"categories": [
{ "name": "Computers", "description": "All computers" },
{ "name": "Electronics", "description": "All electronics" }
],
"manufacturer": {
"address": "One Infinite Loop Cupertino, CA 95014",
"name": "Apple",
"contactNumber": "+1-408-996-1010"
},
"name": "MacBook Pro",
"tags": ["smartphone", "tablet", "laptop"]
}
Here, the manufacturer is grouped into a separate sub-object instead of having its properties at the top level.
@Embeddable(Embeddable.EmbeddableType.GROUPING)
public record Manufacturer(@Column String name, @Column String address, @Column String contactNumber) {}
Flat Structure
A flat structure keeps related information within the same document, embedding lists or nested fields directly. Jakarta NoSQL enables this by using @Embeddable(Embeddable.EmbeddableType.FLAT)
. This approach is beneficial when you want quick access to all details without requiring complex queries.
Example:
{
"_id": { "$oid": "67b22d20c921154b0223b27b" },
"address": "One Infinite Loop Cupertino, CA 95014",
"categories": [
{ "name": "Electronics", "description": "All electronics" },
{ "name": "Computers", "description": "All computers" }
],
"contactNumber": "+1-408-996-1010",
"name": "Apple",
"tags": ["smartphone", "tablet", "laptop"]
}
This approach stores manufacturer details directly in the document instead of grouping them into separate fields.
@Embeddable(Embeddable.EmbeddableType.FLAT)
public record Manufacturer(@Column String name, @Column String address, @Column String contactNumber) {}
Example Usage in Jakarta NoSQL
The following code snippet demonstrates how Jakarta NoSQL integrates these structures:
public class App {
public static void main(String[] args) {
var faker = new Faker();
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
var template = container.select(DocumentTemplate.class).get();
var electronicsCategory = new Category("Electronics", "All electronics");
var computerCategory = new Category("Computers", "All computers");
var tags = List.of("smartphone", "tablet", "laptop");
var manufacturer = new Manufacturer("Apple", "One Infinite Loop Cupertino, CA 95014", "+1-408-996-1010");
Product macBookPro = Product.builder().categories(Set.of(electronicsCategory, computerCategory))
.manufacturer(manufacturer)
.name("MacBook Pro")
.tags(tags)
.build();
Product product = template.insert(macBookPro);
System.out.println("Product saved: " + product);
}
}
}
Choosing the Right Approach
- Use a flat structure when you need a simpler document layout with all properties at the same level.
- Use a grouped structure when organizing related data into logical sub-objects to improve readability and maintainability.
Conclusion
Jakarta NoSQL offers flexibility in structuring MongoDB documents using @Embeddable(Embeddable.EmbeddableType)
. Choosing flat or grouped structures depends on your data access patterns and modeling preferences. Understanding these approaches allows for efficient database design, making queries more effective while keeping your domain model clean and well-structured.
For the complete code, visit the GitHub repository.
Video
Opinions expressed by DZone contributors are their own.
Comments