SoFunction
Updated on 2025-03-04

SpringBoot integrates MongoDB to implement document storage function

1. Introduction to MongoDB

MongoDB (from the English word "Humongous" and Chinese meaning is "Humongous") is an open source database that can be applied to enterprises of all sizes, industries and applications of all kinds. A database based on distributed file storage. Written in C++. Designed to provide scalable, high-performance data storage solutions for WEB applications. MongoDB is a high-performance, open source, schema-free document-based database, and is a popular one in the current NoSql database.

MongoDB is a product between a relational database and a non-relational database. It is the most functional and most similar to a relational database among non-relational databases. The data structure it supports is very loose and is in a json-like bjson format, so it can store relatively complex data types. The biggest feature of MongoDB is that the query language it supports is very powerful. Its syntax is a bit similar to an object-oriented query language. It can almost realize most of the functions similar to single table query of relational databases, and it also supports indexing of data.

Traditional relational databases generally consist of three levels of concepts: database, table, and record. MongoDB is composed of three levels of database, collection, and document object. MongoDB has tables in relational databases, but there are no concepts of columns, rows and relationships in the set, which reflects the characteristics of pattern freedom.

A record in MongoDB is a document, a data structure, composed of field and value pairs. MongoDB documentation is similar to JSON objects. The value of the field may include other documents, arrays, and document arrays. MongoDB supports operating systems such as OS X, Linux and Windows, and provides drivers for Python, PHP, Ruby, Java and C++ languages. The community also provides drivers for platforms such as Erlang and .NET.

MongoDB is suitable for storing large amounts of data in either no fixed format, such as logs, caches, etc. Weak support for things and do not apply to complex multi-document (multiple table) cascading queries. The article demonstrates that Mongodb version is 3.5.

2. MongoDB's addition, deletion, modification and search

Spring Boot encapsulates various popular data sources, including Mongodb, and below will introduce you how to use Mongodb in Spring Boot:

1. Pom package configuration

Add spring-boot-starter-data-mongodb package reference to the pom package

<dependencies>
    <dependency> 
        <groupId></groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency> 
</dependencies>

2. Add configuration in

=mongodb://name:pass@localhost:27017/test

Multiple IP clusters can use the following configuration:

=mongodb://user:pwd@ip1:port1,ip2:port2/database

3. Create a data entity

public class User implements Serializable {
    private static final long serialVersionUID = -3258839839160856613L;
    private Long id;
    private String userName;
    private String passWord;
    //Getter and setter omitted}

4. Create an entity's addition, deletion, modification and search operation

The Repository layer implements the addition, deletion, modification and search of User objects

Component

public class UserRepositoryImpl implements UserRepository {
 
    @Autowired
    private MongoTemplate mongoTemplate;
 
    /**
      * Create an object
      * @param user
      */
    @Override
    public void saveUser(User user) {
        (user);
    }
 
    /**
      * Query objects by username
      * @param userName
      * @return
      */
    @Override
    public User findUserByUserName(String userName) {
        Query query=new Query(("userName").is(userName));
        User user =  (query , );
        return user;
    }
 
    /**
      * Update the object
      * @param user
      */
    @Override
    public long updateUser(User user) {
        Query query=new Query(("id").is(()));
        Update update= new Update().set("userName", ()).set("passWord", ());
        //Update query returns the first item of the result set        UpdateResult result =(query,update,);
        //Update query returns all the result set        // (query,update,);
        if(result!=null)
            return ();
        else
            return 0;
    }
 
    /**
      * Delete the object
      * @param id
      */
    @Override
    public void deleteUserById(Long id) {
        Query query=new Query(("id").is(id));
        (query,);
    }
}

5. Develop corresponding test methods

@RunWith()
@SpringBootTest
public class UserDaoTest {
    @Autowired
    private UserDao userDao;
    @Test
    public void testSaveUser() throws Exception {
        UserEntity user=new UserEntity();
        (2l);
        ("Xiao Ming");
        ("fffooo123");
        (user);
    }
    @Test
    public void findUserByUserName(){
       UserEntity user= ("Xiao Ming");
       ("user is "+user);
    }
    @Test
    public void updateUser(){
        UserEntity user=new UserEntity();
        (2l);
        ("Sky");
        ("fffxxxx");
        (user);
    }
    @Test
    public void deleteUserById(){
        (1l);
    }
}

6. Check the verification results

You can use the tool MongoVUE tool to connect and display it directly graphically, or you can log in to the server to view it with commands.

1) Log in mongos

bin/mongo -host localhost -port 20000

2) Switch to the test library

use test

3) Query user collection data

()

According to the results of the 3 query, we observe whether the execution of the test case is correct.

At this point, the addition, deletion, modification and search functions of Spring Boot corresponding to MongoDB have been fully implemented.

3. Multi-data source MongoDB usage

Next, implement the use of MongoDB multi-data source

1. Pom package configuration

<dependencies>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-data-mongodb</artifactId>
    </dependency>
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-test</artifactId>
    </dependency>
</dependencies>

2. Configure two data sources

as follows:

=mongodb://192.168.0.75:20000
=primary
=mongodb://192.168.0.75:20000
=secondary

3. Configure the data source of the two libraries

Encapsulate reading of two configuration files starting with Mongodb

@Data
@ConfigurationProperties(prefix = "mongodb")
public class MultipleMongoProperties {
 
    private MongoProperties primary = new MongoProperties();
 
    private MongoProperties secondary = new MongoProperties();
}

Configure different data sources under different package paths

Encapsulation of the first library

@Configuration
@EnableMongoRepositories(basePackages = "",mongoTemplateRef = PrimaryMongoConfig.MONGO_TEMPLATE)
public class PrimaryMongoConfig {
    protected static final String MONGO_TEMPLATE = "primaryMongoTemplate";
}

Encapsulation of the second library

@Configuration
@EnableMongoRepositories(basePackages = "",mongoTemplateRef = SecondaryMongoConfig.MONGO_TEMPLATE)
public class SecondaryMongoConfig {
    protected static final String MONGO_TEMPLATE = "secondaryMongoTemplate";
}

Read the corresponding configuration information and construct the corresponding MongoTemplate

@Configuration
public class MultipleMongoConfig {
    @Autowired
    private MultipleMongoProperties mongoProperties;
    @Primary
    @Bean(name = PrimaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate primaryMongoTemplate() throws Exception {
        return new MongoTemplate(primaryFactory(()));
    }
    @Bean
    @Qualifier(SecondaryMongoConfig.MONGO_TEMPLATE)
    public MongoTemplate secondaryMongoTemplate() throws Exception {
        return new MongoTemplate(secondaryFactory(()));
    }
    @Bean
    @Primary
    public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClient((), ()),
                ());
    }
    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception {
        return new SimpleMongoDbFactory(new MongoClient((), ()),
                ());
    }
}

The configuration information of the two libraries has been completed.

4. Create the corresponding objects and Repository of the two libraries respectively

Corresponding can be used together

public class User implements Serializable {
    private static final long serialVersionUID = -3258839839160856613L;
    private String  id;
    private String userName;
    private String passWord;
    public User(String userName, String passWord) {
             = userName;
             = passWord;
    }
}

Corresponding Repository

public interface PrimaryRepository extends MongoRepository<PrimaryMongoObject, String> {
 
}

Inheriting MongoRepository will implement many basic additions, deletions, modifications and searches by default, saving a lot of code written by yourself in the Repository layer.

Secondary is similar to the above code and will not be posted

5. Final test

@RunWith()
@SpringBootTest
public class MuliDatabaseTest {
    @Autowired
    private PrimaryRepository primaryRepository;
    @Autowired
    private SecondaryRepository secondaryRepository;
    @Test
    public void TestSave() {
        ("************************************************************");
        ("Testing Begins");
        ("************************************************************");
        
                .save(new PrimaryMongoObject(null, "Object of the first library"));
        
                .save(new SecondaryMongoObject(null, "Object of the second library"));
        List&lt;PrimaryMongoObject&gt; primaries = ();
        for (PrimaryMongoObject primary : primaries) {
            (());
        }
        List&lt;SecondaryMongoObject&gt; secondaries = ();
        for (SecondaryMongoObject secondary : secondaries) {
            (());
        }
        ("************************************************************");
        ("Test completed");
        ("************************************************************");
    }
}

At this point, the use of MongoDB multi-data sources has been completed.

The above is the detailed content of SpringBoot integrating MongoDB to implement document storage functions. For more information about SpringBoot MongoDB document storage, please pay attention to my other related articles!