You are currently viewing mongodbEssential Spring Data MongoDB Annotations: Mapping Java Classes to MongoDB Documents with Examplesmongodb

mongodbEssential Spring Data MongoDB Annotations: Mapping Java Classes to MongoDB Documents with Examplesmongodb

In MongoDB with Spring Data, various annotations are used to map Java classes to MongoDB documents and configure how the data is stored and retrieved. Below are the key annotations provided by Spring Data MongoDB along with examples of how to use them:

1. @Document

The @Document annotation is used to mark a class as a MongoDB document, which will be stored in a MongoDB collection.

Example:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {

    @Id
    private String id;
    private String name;
    private String email;

    // Getters and setters
}
  • collection: Specifies the collection name. If not provided, the class name is used as the collection name.

2. @Id

The @Id annotation is used to mark the field that will be used as the identifier for the document in MongoDB.

Example:

import org.springframework.data.annotation.Id;

public class User {

    @Id
    private String id;
    private String name;
    private String email;

    // Getters and setters
}
  • The field annotated with @Id will typically map to the _id field in the MongoDB document.

3. @Field

The @Field annotation is used to specify the field name in the MongoDB document that the Java field should be mapped to.

Example:

import org.springframework.data.mongodb.core.mapping.Field;

public class User {

    @Id
    private String id;

    @Field("username")
    private String name;

    @Field("user_email")
    private String email;

    // Getters and setters
}
  • In this example, the name field in Java is mapped to username in the MongoDB document, and email is mapped to user_email.

4. @Transient

The @Transient annotation is used to indicate that a field should not be persisted in the MongoDB document.

Example:

import org.springframework.data.annotation.Transient;

public class User {

    @Id
    private String id;
    private String name;
    private String email;

    @Transient
    private String tempPassword;

    // Getters and setters
}
  • The tempPassword field will not be stored in the MongoDB collection.

5. @Indexed

The @Indexed annotation is used to create an index on the annotated field. This can improve query performance.

Example:

import org.springframework.data.mongodb.core.index.Indexed;

public class User {

    @Id
    private String id;

    @Indexed(unique = true)
    private String email;

    private String name;

    // Getters and setters
}
  • unique: Ensures that the indexed field will have unique values across documents.

6. @CompoundIndex

The @CompoundIndex annotation is used to create a compound index, which is an index on multiple fields.

Example:

import org.springframework.data.mongodb.core.index.CompoundIndex;
import org.springframework.data.mongodb.core.index.CompoundIndexes;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
@CompoundIndexes({
    @CompoundIndex(name = "email_name_idx", def = "{'email': 1, 'name': 1}")
})
public class User {

    @Id
    private String id;
    private String email;
    private String name;

    // Getters and setters
}
  • def: Specifies the fields that make up the compound index.

7. @DBRef

The @DBRef annotation is used to create a reference to another document in a different collection.

Example:

import org.springframework.data.mongodb.core.mapping.DBRef;

public class User {

    @Id
    private String id;
    private String name;

    @DBRef
    private Address address;

    // Getters and setters
}
  • In this example, the address field is a reference to a document in another collection.

8. @PersistenceConstructor

The @PersistenceConstructor annotation is used to indicate a constructor that Spring Data MongoDB should use when instantiating the object from the database.

Example:

import org.springframework.data.annotation.PersistenceConstructor;

public class User {

    @Id
    private String id;
    private String name;
    private String email;

    @PersistenceConstructor
    public User(String id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    // Getters and setters
}
  • This constructor will be used when creating an instance of User from the database.

9. @Version

The @Version annotation is used to handle optimistic locking by storing the version of the document. Each update increments the version number, and updates are rejected if the version number doesn’t match.

Example:

import org.springframework.data.annotation.Version;

public class User {

    @Id
    private String id;
    private String name;

    @Version
    private Long version;

    // Getters and setters
}
  • This ensures that concurrent updates don’t overwrite each other unexpectedly.

10. @TextIndexed

The @TextIndexed annotation is used to create a text index on the annotated field, which allows for text search capabilities.

Example:

import org.springframework.data.mongodb.core.index.TextIndexed;

public class Article {

    @Id
    private String id;

    @TextIndexed
    private String title;

    @TextIndexed
    private String content;

    // Getters and setters
}
  • This enables full-text search on the title and content fields.

Summary

These annotations help you map your Java objects to MongoDB documents, define indexes, create references, and manage document versions effectively. By using these annotations appropriately, you can ensure that your application’s interaction with MongoDB is both efficient and aligned with your data model.
Certainly! Below are a few more advanced annotations and concepts in MongoDB with Spring Data:

11. @GeoSpatialIndexed

The @GeoSpatialIndexed annotation is used to create a geospatial index on a field, which allows for queries based on geographical data like latitude and longitude.

Example:

import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection = "places")
public class Place {

    @Id
    private String id;

    private String name;

    @GeoSpatialIndexed
    private double[] location; // [longitude, latitude]

    // Getters and setters
}
  • This annotation enables geospatial queries like finding documents within a certain radius.

12. @GeoSpatialIndexed (2D Sphere)

For more accurate geospatial calculations on a spherical model (like Earth), you can specify the index type as 2dsphere.

Example:

import org.springframework.data.mongodb.core.index.GeoSpatialIndexed;

public class Place {

    @Id
    private String id;

    private String name;

    @GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
    private double[] location; // [longitude, latitude]

    // Getters and setters
}
  • This is particularly useful for applications involving map data, like finding nearby locations.

13. @Sharded

The @Sharded annotation is used in environments where MongoDB collections are sharded across multiple servers. This annotation allows specifying the shard key.

Example:

import org.springframework.data.mongodb.core.mapping.Sharded;

@Document(collection = "users")
@Sharded(shardKey = { "email" })
public class User {

    @Id
    private String id;
    private String email;
    private String name;

    // Getters and setters
}
  • shardKey: Defines the fields that should be used as the shard key.

14. @CascadeSave

The @CascadeSave annotation is not a built-in Spring Data annotation, but it’s a common pattern implemented to handle cascading saves in relationships between documents.

Example:

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
public class User {

    @Id
    private String id;
    private String name;

    @DBRef
    @CascadeSave
    private Address address;

    // Getters and setters
}
  • This custom annotation can be implemented to ensure that when a User is saved, the related Address document is also saved automatically.

15. @MongoId

@MongoId is a more flexible annotation introduced in Spring Data MongoDB 3.0. It is an alternative to @Id that allows for more control over the ID mapping.

Example:

import org.springframework.data.annotation.MongoId;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.MongoId.FieldType;

@Document(collection = "users")
public class User {

    @MongoId(FieldType.OBJECT_ID)
    private String id;

    private String name;
    private String email;

    // Getters and setters
}
  • FieldType: Specifies the type of the ID field, such as OBJECT_ID, STRING, or LONG.

16. @Persistent

The @Persistent annotation is used to mark a class or field as persistent, making it eligible for mapping by Spring Data MongoDB.

Example:

import org.springframework.data.annotation.Persistent;

@Persistent
public class Address {

    private String city;
    private String country;

    // Getters and setters
}
  • This annotation can be used to control the persistence behavior in more complex mappings.

17. @ReadPreference

The @ReadPreference annotation allows you to specify the preferred replica set member to read from in a replica set environment.

Example:

import org.springframework.data.mongodb.core.mapping.ReadPreference;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "users")
@ReadPreference(ReadPreferenceType.SECONDARY_PREFERRED)
public class User {

    @Id
    private String id;
    private String name;
    private String email;

    // Getters and setters
}
  • ReadPreferenceType: This can be PRIMARY, PRIMARY_PREFERRED, SECONDARY, SECONDARY_PREFERRED, or NEAREST.

18. @TimeSeries

The @TimeSeries annotation is used to define a time-series collection in MongoDB, which is optimized for storing time-series data like metrics or logs.

Example:

import org.springframework.data.mongodb.core.mapping.TimeSeries;

@Document(collection = "sensor_data")
@TimeSeries(timeField = "timestamp", metaField = "type", granularity = TimeSeriesGranularity.SECONDS)
public class SensorData {

    @Id
    private String id;

    private String type;
    private double value;
    private long timestamp;

    // Getters and setters
}
  • timeField: The field that stores the timestamp for each document.
  • metaField: Optional field used to store metadata.
  • granularity: Defines the granularity of the time-series collection (seconds, minutes, hours).

19. @TextScore

The @TextScore annotation allows you to retrieve the relevance score of a text search query in MongoDB.

Example:

import org.springframework.data.mongodb.core.mapping.TextScore;

public class Article {

    @Id
    private String id;

    private String title;
    private String content;

    @TextScore
    private Float score;

    // Getters and setters
}
  • The score field will hold the relevance score when performing a text search query.

20. @AfterConvert and @BeforeConvert

These annotations are used for lifecycle events, allowing you to hook into the conversion process before or after converting a document to an entity.

Example:

import org.springframework.data.mongodb.core.mapping.event.BeforeConvertCallback;
import org.springframework.stereotype.Component;

@Component
public class UserEntityCallback implements BeforeConvertCallback<User> {

    @Override
    public User onBeforeConvert(User user, String collection) {
        // Modify the entity before it is converted to a MongoDB document
        user.setName(user.getName().toUpperCase());
        return user;
    }
}
  • @BeforeConvert: Invoked before converting a document to an entity.
  • @AfterConvert: Invoked after converting a document to an entity.

Summary

These additional annotations and concepts in Spring Data MongoDB allow you to manage more complex data models and operations effectively. Whether you’re dealing with geospatial data, sharded collections, or time-series data, these tools provide a robust foundation for working with MongoDB in a Spring application.

Leave a Reply