Recently, due to team adjustment, I spent most of my time on the team, and the update of this series was delayed again. But since the promise of continuous updates, that will not be left behind, starting today to continue to update this part of the content!

Over the next year, to restate the goal of the series: the main task now is to upgrade everything in Spring Boot 1.x that hasn’t been upgraded. I’ll explain some of the changes that have occurred as a result of the version upgrade, so that readers of both the lower version and the higher version can find what they want. This is also an important reason for doing the 2.x update this time, to try to avoid or reduce the number of readers who have problems with the older version of my implementation, and then start asking about my family.

With all of these updates in place, the next major updates will focus on the more advanced aspects of Spring Boot, such as what extensions to make and where to start.

If you are a Spring Boot user, pay attention! The following content will be more and more exciting!

Back to today’s topic, how to use MongoDB in Spring Boot!

Directing a profile

Directing is a database based on distributed file storage, it is a between relational databases and the relational database products, its main target is the key/value storage (provides high performance and high scalability) and the traditional RDBMS system (with rich functions) provides the bridge between, it combines the advantages of both in one.

MongoDB supports a loose data structure in THE Bson format similar to JSON, so it can store complex data types, and its storage format also makes it very smooth to use the data stored in Nodejs applications.

Since it is called NoSQL database, Mongo’s query language is very powerful, its syntax is somewhat similar to object-oriented query language, can almost achieve most functions similar to relational database single table query, but also supports the index of data.

However, MongoDB is not a panacea. Compared with MySQL and other relational databases, they have their own unique advantages for different data types and transaction requirements. In the choice of data storage, adhere to the principle of diversification, choose a better and more economical way, rather than top-down unification.

More commonly, we can directly use MongoDB to store key-value pair data, such as: verification code, Session, etc. Due to the horizontal expansion capability of MongoDB, it can also be used to store huge data whose scale will change in the future, such as logs and comments. Due to the weak type of data stored in MongoDB, it can also be used to store some variable JSON data, such as JSON packets that change frequently when interacting with external systems. However, for some operations with complex and high transactional requirements on data, such as account transactions, it is not suitable to use MongoDB for storage.

MongoDB website: www.mongodb.org/

Began to try

Step 1: Introduce dependencies

In Spring Boot, you can add spring-boot-starter-data-mongodb to pem. XML to enable mongodb access. Its implementation relies on spring-data-mongodb. Spring-data-jpa, spring-data-redis, spring-data also provides powerful support for mongodb access, so let’s start with a try.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
Copy the code

Step 2: Create the User entity User

@Data
public class User {

    @Id
    private Long id;

    private String username;
    private Integer age;

}
Copy the code

Step 3: Implement a data access object UserRepository for User entity User

public interface UserRepository extends MongoRepository<User.Long> {

    User findByUsername(String username);

}
Copy the code

Under the Spring Data abstraction, is it as simple, easy to use, and easy to learn as other Spring Data subprojects?

Step 4: Write unit tests

@SpringBootTest(classes = Chapter61Application.class)
public class ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test(a) throws Exception {
        userRepository.deleteAll();

        // Create three users and verify the total number of users
        userRepository.save(new User(1L."didi".30));
        userRepository.save(new User(2L."mama".40));
        userRepository.save(new User(3L."kaka".50));
        Assertions.assertEquals(3, userRepository.findAll().size());

        // Delete a User and verify the total number of users
        User u = userRepository.findById(1L).get();
        userRepository.delete(u);
        Assertions.assertEquals(2, userRepository.findAll().size());

        // Delete a User and verify the total number of users
        u = userRepository.findByUsername("mama");
        userRepository.delete(u);
        Assertions.assertEquals(1, userRepository.findAll().size()); }}Copy the code

Note that the Assertions used here are integrated since Spring Boot 2.4, prior to which Assert was used

Step 5: Configure parameters

In the example above, it is easy to access MongoDB, but in practice, application servers and MongoDB are usually not deployed on the same device and therefore cannot be used with automatic local configuration. In this case, we can easily configure the mongodb server to support the application. Properties, as shown in the following example:

spring.data.mongodb.uri=mongodb://name:pass@localhost:27017/test
Copy the code

When trying this configuration, remember to create a user with read and write permission for the test library in Mongo (the user name is name, and the password is pass)

If mongodb 2.x is used, you can also set the following parameters.

spring.data.mongodb.host=localhost spring.data.mongodb.port=27017
Copy the code

digression

MongoDB has received a lot of attention in the past, but due to its mediocrity in all aspects, it seems to be less heard or seen in large-scale scenarios recently. As far as the author is concerned, many of the previous usage scenarios are also starting to use ES instead, in order to obtain better performance.

So, next time we’ll talk about using ES in Spring Boot. Follow me and keep getting more Spring Boot technical stuff!

More free tutorials in this series”Click to go to summary directory”

Code sample

For an example of this article, see the chapter6-1 directory in the repository below:

  • Github:github.com/dyc87112/Sp…
  • Gitee:gitee.com/didispace/S…

If you found this article good, welcomeStarSupport, your attention is my motivation!

Welcome to pay attention to my public account: Program monkey DD, get the exclusive arrangement of learning resources, daily dry goods and welfare gifts.