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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Translating OData Queries to MongoDB in Java With Jamolingo
  • Custom Attributes in Relational Databases

Trending

  • Managing Technical Debt in AI-Generated Code
  • When 12 Hours of Offline Changes Collide: Designing Conflict-Safe Mobile Sync
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • The Self-Hosting Math Changed While We Were Still Arguing About Sovereignty

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Databases
  4. Generating MongoDB Annotations for Java POJOs from JSON Schema Using the JSONSchema2Pojo Plugin

Generating MongoDB Annotations for Java POJOs from JSON Schema Using the JSONSchema2Pojo Plugin

This article explains how to generate MongoDB annotations for Java classes using the JsonSchema2Pojo plugin with a schema.

By 
Venugopal Reddy Modhugu
·
May. 04, 23 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
7.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

MongoDB is a popularly used NoSQL database that stores data in a document format. Each record in MongoDB is a collection of key-value pairs. JSONSchema2Pojo is a popular Java tool that generates Java classes from JSON schema, which are typically used for data serialization and deserialization. While this plugin generates Jackson annotations for serialization and deserialization by default, it's also possible to utilize it for generating custom annotations. In this article, we will demonstrate how to generate MongoDB annotations using this plugin.

When working with MongoDB, Java objects are commonly used to represent collections and documents. To insert data into MongoDB using the Spring framework, it's necessary to generate POJO classes based on the collection schema. The Spring framework is a popular Java framework used to build backend applications and provides support for MongoDB integration. 

Even if the incoming data is in PascalCase format, the Java classes' field names will be in camelCase. This can lead to issues when inserting data into MongoDB, as the data will be stored with camelCase field names. To avoid this issue, Mongo annotations can be added using the JSONSchema2Pojo plugin. These annotations allow us to specify the desired field names in the generated Java classes, which will then be used when inserting data into MongoDB.

The annotations provided by MongoDB are used to specify how the Java fields map to the corresponding MongoDB document fields. The most commonly used annotations are:

@Document — Used to specify the MongoDB collection name that the Java class maps to.

@Id — Used to specify the primary key field in the Java class that maps to the _id field in MongoDB.

@Field — Used to specify the MongoDB field name that the Java field maps to.


Follow These Steps To Generate Mongo Annotations

Step 1 

To use the JSONSchema2Pojo plugin to add custom annotations, a custom annotator class needs to be created. This can be done as a separate project and then included in the actual project. In case the project is a multi-module project, the custom annotator class can be created as a separate module. 

Step 2

Add the necessary dependencies in the Maven file.

XML
 
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>3.4.8</version>
</dependency>
<dependency>
    <groupId>org.jsonschema2pojo</groupId>
    <artifactId>jsonschema2pojo-core</artifactId>
    <version>1.2.1</version>
</dependency>


Step 3

Create a custom annotator class that extends the AbstractAnnotator class. The custom annotator class can override the propertyField() method to annotate each Java field with the appropriate MongoDB annotation

Here is an example custom annotator class:

Java
 
public class customMongoPojoAnnotations extends AbstractAnnotator {
    List<String> primaryKeyFields;
    public customMongoAnnotations() {
        primaryKeyFields = new ArrayList<String>();
        primaryKeyFields.add("_id");
    }
    @Override
    public void propertyField(JFieldVar field, JDefinedClass clazz, String propertyName, JsonNode propertyNode) {
        super.propertyField(field, clazz, propertyName, propertyNode);
        if (primaryKeyFields.contains(propertyName)) {
            field.annotate(Id.class);
        }
        field.annotate(Field.class).param("value", propertyName);
    }

    @Override
    public void propertyOrder(JDefinedClass clazz, JsonNode propertyNode){
        clazz.annotate(Document.class);
    }
}


By default, MongoDB uses the _id field as the primary key. If we want to use a different field as the primary key in MongoDB, we can configure it in the config file and provide it to the custom annotator class. By making the necessary modifications to the code, we can generate the appropriate @Id annotations for the designated field

Step 4

Add this class in the JSONSchema2pojo plugin configuration of the actual project using the customAnnotator property. This will ensure that the custom annotations are added to the generated classes.

XML
 
<build>
        <plugins>
    <plugin>
        <groupId>org.jsonschema2pojo</groupId>
        <artifactId>jsonschema2pojo-maven-plugin</artifactId>
        <version>1.2.1</version>
        <dependencies>
            <dependency>
                <artifactId>MongoAnnotationsHelper</artifactId>
                <groupId>org.example</groupId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>
        <configuration>
            <sourceDirectory>${basedir}/src/main/resources</sourceDirectory>
            <targetPackage>com.example.generated</targetPackage>
            <customAnnotator>com.example.customMongoPojoAnnotations</customAnnotator>
        </configuration>
        <executions>
            <execution>
                <goals>
                    <goal>generate</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
        </plugins>
    </build>


The JSON Schema is located in the project's "src/main/resources" folder.
Sample JSON schema:

JSON
 
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Employee",
  "type": "object",
  "properties": {
    "_id": {
      "type": "object",
      "properties": {
        "$oid": {
          "type": "string"
        }
      },
      "description": "The unique identifier for the document.",
      "example": { "$oid": "60a6f8b6e01cd7bf3c0485c3" }
    },
    "EmployeeId": {
      "type": "integer",
      "description": "The unique identifier for the employee."
    },
    "FirstName": {
      "type": "string",
      "description": "The first name of the employee."
    },
    "LastName": {
      "type": "string",
      "description": "The last name of the employee."
    },
    "Email": {
      "type": "string",
      "description": "The email address of the employee."
    },
    "PhoneNumber": {
      "type": "string",
      "description": "The phone number of the employee."
    },
    "Address": {
      "type": "object",
      "properties": {
        "Street": {
          "type": "string",
          "description": "The street address of the employee."
        },
        "City": {
          "type": "string",
          "description": "The city where the employee resides."
        },
        "State": {
          "type": "string",
          "description": "The state where the employee resides."
        },
        "Zip": {
          "type": "string",
          "description": "The ZIP code of the employee's address."
        }
      },
      "required": ["Street", "City", "State", "Zip"],
      "description": "The employee's address information."
    }
  },
  "required": ["_id", "EmployeeID", "FirstName", "LastName", "Email", "PhoneNumber", "Address"],
  "description": "The schema for storing employee and address information in a MongoDB collection."
}


This will generate the necessary MongoDB annotations using the @Document, @Field, and @Id annotations. This allows the data to be properly mapped to Java POJOs with camelCase letters and then persisted to MongoDB with the field names defined in the schema.

Conclusion

By following the steps outlined in this article, one can generate the required MongoDB annotations using the JSONSchema2Pojo plugin with a custom annotator class. This custom annotation approach can also be applied to generate other annotations while generating Java classes with the plugin.

JSON MongoDB Java (programming language) Schema

Opinions expressed by DZone contributors are their own.

Related

  • Replacing JSON With Protobuf in Your Microservice Mesh: A Zero-Downtime Migration Blueprint
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Translating OData Queries to MongoDB in Java With Jamolingo
  • Custom Attributes in Relational Databases

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook