This is the 17th day of my participation in Gwen Challenge
Spring Data for MongoDB is part of the Spring Data project, which aims to provide a familiar and consistent Spring-based programming model for new Data stores while preserving storage-specific features and functionality. In this article, I’ll show you how to use this framework.
After reading this article, you will understand:
- Why use Spring Data MongoDB?
- How to install?
- How do I create poJOs?
- How do I create a service?
- How do I configure MongoDB?
- How to test?
Let’s get started without delay.
purpose
Why use Spring Data MongoDB? The Spring Data MongoDB project provides integration with the MongoDB document database. The key feature of Spring Data MongoDB is a POJO-centric model for interacting with MongoDB DBCollection and writing a Repository style Data access layer easily.
- Spring configuration support: Java-based
@Configuration
Class or XML namespace-based configuration to drive Mongo instances and replicas. - MongoTemplate helper class: Increases the efficiency of performing common Mongo operations, including integrated object mapping between documents and POJOs.
- Exception handling: Exceptions are translated into Spring’s portable data access exception hierarchy
- Feature-rich object mapping integrates with Spring’s transformation services
- Annotation-based mapping metadata, and extensible to support other metadata formats
- Persist and map life cycle events
- Use low-level mapping of the MongoReader/MongoWriter abstraction
- Java-based query, condition, and update DSLS
- Automatic implementation of the Repository interface, including support for custom query methods.
- QueryDSL integration to support type-safe queries, and geospatial integration
- The Map – Reduce integration
- JMX administration and monitoring
- CDI support for repositories
- Support the GridFS
The installation
This article mainly uses spring-boot-starter-data-mongodb, which can be combined with Spring data and Spring Boot.
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> The < version > 2.5.2 < / version > < / dependency >Copy the code
Maven relies on mongodb driver-sync 4.2.3 and Spring-data-mongodb 3.2.2. They then have their own dependencies, mainly using Spring 5.3:
mvn dependency:tree ... [INFO] + - org. Springframework. The boot: spring - the boot - starter - data - mongo: jar: 2.5.2: compile [INFO] | + - Org. Mongo: directing a driver - sync: jar: holdings: compile [INFO] | | + - org. Mongo: bson: jar: holdings: compile [INFO] | | \ - Org. Mongo: directing a driver - the core: jar: holdings: compile | \ [INFO] - Org. Springframework. Data: spring - data - mongo: jar: 3.2.2: compile [INFO] | + - Org. Springframework: spring - tx: jar: 5.3.8: compile [INFO] | + - org. Springframework: spring - the context: jar: 5.3.8: compile/INFO | | \ - org. Springframework: spring aop: jar: 5.3.8: compile [INFO] | + - org. Springframework: spring - beans: jar: 5.3.8: compile [the INFO] | + - org. Springframework: spring - expression: jar: 5.3.8: compile | \ [INFO] - Org. Springframework. Data: spring - data - Commons: jar: 2.5.2: compileCopy the code
The current version is used here. But depending on your situation, you may need to choose another version. If it’s an existing project, several constraints you may encounter are the existing version of the Spring project, the existing version of Spring Boot, and the MongoDB version.
In the following paragraphs, we will use Person as an example to show how to create poJOs, create services, configure MongoDB, and test.
Create a POJO
You first need a Java class to represent the documents in the Mongo Collection. For example, a Person class might have three fields: name, age, and document ID. This information can be expressed in the following ways:
import lombok.*;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.mapping.Document;
@Getter
@EqualsAndHashCode
@ToString
@Builder
@Document(collection = "people")
public class Person {
private final String name;
private final int age;
private @Getter ObjectId id;
}
Copy the code
Lombok is used as the framework. The main purpose of doing this is to avoid writing getters/setters and generating hashcode/equal/toString. On the one hand, it makes the code more concise, and on the other hand, it avoids errors due to incorrect implementation. The Builder function is also used here, because in real projects poJOs often have many fields, and if you use the constructor directly instead of builder, it can be very error-prone. If you want to clone an existing instance and modify it slightly, you can’t do it without Builder.
To use Lombok, in addition to the Java code above, you need to add Lombok libraries to your projects. If you are a Maven project, you can add it as follows:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
Copy the code
Its scope is provided, which means that it is only required for compilation. Lombok modiates code for your project through the Java compiler’s annotation processor, so it doesn’t need to stay in the classpath after compilation.
Create a service
Create a spring-based data Service @service to communicate with MongoDB. For example, use the information “name” to find the corresponding person:
@Service public class PersonService { @Autowired MongoOperations operations; public Optional<Person> findPerson(String name) { var p = operations.findOne(query(where("name").is(name)), Person.class); return Optional.ofNullable(p); }}Copy the code
The Mongo operation is easy to understand. The corresponding Mongo Shell script is:
db.people.findOne({ name: input_name })
Copy the code
Creating the MongoDB Configuration
Create mongo client need a java-based @ Bean, then this method needs to return a com. The mongo. Client. MongoClient instance. But this is not the only way, I think the comparison method is to use inheritance String Data Mongo AbstractMongoClientConfiguration abstract class, because it can provides many configuration options, in the form of a Java method. The specific annotations are already implemented in the abstract class, so as users we only need to focus on the parameters we want to modify, such as the database name, connection string, and so on. In the following example, I have connected to the localhost MongoDB database demo:
@Configuration public class MongoConfig extends AbstractMongoClientConfiguration { @Override public MongoClient mongoClient() { return MongoClients.create("mongodb://localhost:27017"); } @Override protected String getDatabaseName() { return "demo"; }}Copy the code
test
Testing is easy. If you use Spring Boot, you can use the spring-boot-starter-test library to help with testing:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
<scope>test</scope>
</dependency>
Copy the code
If you use this library, annotate @SpringbooTtest with the relevant classes that need to be tested, and you can use it. If you need to use these classes during testing, inject them into your tests via @AutoWired. The following test is a simple example of how to create two people and query their existence by name:
@SpringBootTest(classes = {PersonService.class, MongoConfig.class}) class PersonServiceTest { @Autowired MongoOperations operations; @Autowired PersonService personService; Person sansa, arya; @BeforeEach void setUp() { this.sansa = Person.builder().name("Sansa Stark").age(20).build(); this.arya = Person.builder().name("Arya Stark").age(20).build(); operations.save(sansa); operations.save(arya); assertThat(operations.findAll(Person.class)).hasSize(2); } @AfterEach void tearDown() { operations.remove(new Query(), Person.class); } @Test void queryId() { var optPerson = personService.findPerson("Sansa Stark"); assertThat(optPerson).hasValue(sansa); }}Copy the code
For MongoDB, I used a Docker container strategy: start a Docker container for the tests before all the tests start and then clean up the database at the end of the tests. I guess there are other ways, so please leave a comment.
extension
How to expand from this article?
- For more information on Spring Data MongoDB, please visit Spring Data MongoDB – Reference Documentation (3.2.2).
- If you want to know more about Lombok’s features, you are advised to visit Lombok Features
- If you want to learn more about how Mongo Shell works, visit Collection Methods