📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. @Document
@Document(collection = "users")
public class User {
// Class fields and methods
}
2. @Id
This annotation is applied to a field that should be used as the primary key of the document. MongoDB stores the primary key as _id. When using @Id, Spring Data automatically translates the field into _id during persistence.
public class User {
@Id
private String id;
// Other class fields
}
3. @Field
public class User {
@Field(name = "email_address")
private String emailAddress;
// Other fields
}
4. @DBRef
public class Order {
@DBRef
private User user;
// Other fields
}
5. @Query
public interface UserRepository extends MongoRepository<User, String> {
@Query("{ 'emailAddress' : ?0 }")
List<User> findByEmailAddress(String emailAddress);
}
6. @EnableMongoRepositories
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfig {
// Configuration details
}
Complete Example - Simple Book Library System
Let's create a comprehensive example that combines all the discussed Spring Data MongoDB annotations (@Document, @Id, @Field, @DBRef, @Query, and @EnableMongoRepositories) into a single, coherent application. This example will simulate a simple book library system, where we have Book and Author entities, and we aim to showcase how these annotations work together in a Spring Boot application context.Step 1: Define the Domain Models
@Document(collection = "authors")
public class Author {
@Id
private String id;
@Field(name = "name")
private String name;
// Constructors, Getters, and Setters
}
@Document(collection = "books")
public class Book {
@Id
private String id;
@Field(name = "title")
private String title;
@DBRef
private Author author;
// Constructors, Getters, and Setters
}
Step 2: Create Repository Interfaces
public interface AuthorRepository extends MongoRepository<Author, String> {
}
public interface BookRepository extends MongoRepository<Book, String> {
@Query("{ 'title' : ?0 }")
List<Book> findByTitle(String title);
}
Step 3: Configure MongoDB Repositories
@Configuration
@EnableMongoRepositories(basePackages = "com.example.repository")
public class MongoConfig {
// MongoDB configuration details
}
Step 4: Spring Boot Application Setup
@SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
@Bean
CommandLineRunner runner(AuthorRepository authorRepository, BookRepository bookRepository) {
return args -> {
Author author = new Author();
author.setName("Ramesh");
author = authorRepository.save(author);
Book book = new Book();
book.setTitle("Spring Boot for Beginners");
book.setAuthor(author);
bookRepository.save(book);
System.out.println("Sample data loaded");
};
}
}
This complete example illustrates how to use Spring Data MongoDB annotations to define domain models (@Document, @Id, @Field), manage document references (@DBRef), execute custom queries (@Query), and configure MongoDB repositories (@EnableMongoRepositories) in a Spring Boot application. With this setup, you can start building sophisticated, data-driven applications leveraging MongoDB with minimal boilerplate code and maximum efficiency.
Comments
Post a Comment
Leave Comment