DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Understanding Polyglot Persistence
  • Navigating NoSQL: A Pragmatic Approach for Java Developers

Trending

  • Scaling Microservices With Docker and Kubernetes on Production
  • Using Java Stream Gatherers To Improve Stateful Operations
  • Advancing Your Software Engineering Career in 2025
  • Efficient API Communication With Spring WebClient
  1. DZone
  2. Coding
  3. Java
  4. Handling Embedded Data in NoSQL With Java

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.

By 
Otavio Santana user avatar
Otavio Santana
DZone Core CORE ·
Feb. 27, 25 · Analysis
Likes (5)
Comment
Save
Tweet
Share
6.0K Views

Join the DZone community and get the full member experience.

Join For Free

NoSQL 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:

Java
 
@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:

JSON
 
{
  "_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.

Java
 
@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:

JSON
 
{
  "_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.

Java
 
@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:

Java
 
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


Database Database design NoSQL Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Jakarta NoSQL 1.0: A Way To Bring Java and NoSQL Together
  • Simplify NoSQL Database Integration in Java With Eclipse JNoSQL 1.1.3
  • Understanding Polyglot Persistence
  • Navigating NoSQL: A Pragmatic Approach for Java Developers

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!