Spring Boot Tutorial
Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)
Prerequisite (Spring Core Concepts)
Spring Boot Core
Spring Boot with REST API
Spring Boot with Database and Data JPA
Spring Boot with Kafka
Spring Boot with AOP
To integrate MongoDB with a Spring Boot Maven project, you'll use the Spring Data MongoDB project. Here's a step-by-step guide to set this up:
Firstly, add the required dependencies to your pom.xml
:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency>
If you intend to use an embedded MongoDB for testing purposes, you can also include:
<dependency> <groupId>de.flapdoodle.embed</groupId> <artifactId>de.flapdoodle.embed.mongo</artifactId> <scope>test</scope> </dependency>
Update your application.properties
or application.yml
with the necessary MongoDB configurations:
# MongoDB properties spring.data.mongodb.uri=mongodb://localhost:27017/mydatabase
Replace mydatabase
with the name of your database, and adjust the host and port if necessary.
Instead of JPA's @Entity
, in MongoDB you'll use the @Document
annotation for your model classes:
import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document public class User { @Id private String id; private String name; private String email; // Getters, setters, constructors... }
Spring Data MongoDB provides the MongoRepository
interface which offers CRUD operations:
import org.springframework.data.mongodb.repository.MongoRepository; public interface UserRepository extends MongoRepository<User, String> { // Additional query methods (if needed) }
Inject the repository into your service classes and use it:
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Optional; @Service public class UserService { @Autowired private UserRepository userRepository; public Iterable<User> getAllUsers() { return userRepository.findAll(); } public Optional<User> getUserById(String id) { return userRepository.findById(id); } public User saveUser(User user) { return userRepository.save(user); } // Other CRUD operations... }
After you've set everything up, run your Spring Boot application. With the given configurations and code, your application will connect to MongoDB and perform CRUD operations as required.
de.flapdoodle.embed.mongo
), remember it's typically for testing purposes and shouldn't be used in production.Setting up a Maven project with Spring Boot and MongoDB:
pom.xml
with dependencies:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies>
Configuring MongoDB connection in Spring Boot Maven project:
application.properties
file.spring.data.mongodb.host=localhost spring.data.mongodb.port=27017 spring.data.mongodb.database=your_database_name
Spring Data MongoDB repository in a Maven project:
MongoRepository
for MongoDB CRUD operations.public interface YourEntityRepository extends MongoRepository<YourEntity, String> { // Custom queries or additional methods can be defined here }
CRUD operations with MongoDB in Spring Boot Maven project:
@Service public class YourEntityService { @Autowired private YourEntityRepository entityRepository; public YourEntity saveEntity(YourEntity entity) { return entityRepository.save(entity); } public YourEntity getEntityById(String id) { return entityRepository.findById(id).orElse(null); } public List<YourEntity> getAllEntities() { return entityRepository.findAll(); } public void deleteEntity(String id) { entityRepository.deleteById(id); } }
Entity mapping for MongoDB documents in Spring Boot:
@Document(collection = "your_entity_collection") public class YourEntity { @Id private String id; // Other document fields and annotations }
MongoTemplate usage in Spring Boot with Maven:
MongoTemplate
for more complex queries and MongoDB operations.@Service public class YourEntityService { @Autowired private MongoTemplate mongoTemplate; public List<YourEntity> customQuery() { Query query = new Query(Criteria.where("someField").is("someValue")); return mongoTemplate.find(query, YourEntity.class); } }
Indexing and optimization for MongoDB in Spring Boot:
@Document(collection = "your_entity_collection") @CompoundIndex(def = "{'field1': 1, 'field2': -1}") public class YourEntity { // Entity fields and annotations }
Handling relationships and references in MongoDB with Spring Boot:
@DBRef
or embedding documents.@Document(collection = "parent_entity_collection") public class ParentEntity { @Id private String id; @DBRef private List<ChildEntity> children; // Other fields and annotations } @Document(collection = "child_entity_collection") public class ChildEntity { @Id private String id; // Child entity fields and annotations }
Testing MongoDB integration in a Spring Boot Maven project:
@DataMongoTest
.@RunWith(SpringRunner.class) @DataMongoTest public class YourEntityRepositoryTest { @Autowired private YourEntityRepository entityRepository; @Test public void testCRUDOperations() { // Your test logic here } }