Spring Boot 技术探索

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

31、Spring Boot之MongoDB的简单使用

平台环境:

名称

版本号

Mac OS X

10.15.1

JDK

1.8.0_201

Apache Maven

3.6.0

IntelliJ IDEA

2019.3 (Ultimate Edition)

Spring Boot

2.2.2.RELEASE

MongoDB

Community Edition 4.2

 

  什么是MongoDB?

  MongoDB 如今是最流行的 NoSQL 数据库。

 

  MongoDB 相关概念

SQL 术语/概念

MongoDB 术语/概念

解释/说明

DataBase

DataBase

数据库

Table

Collection

数据库表/集合

Row

Document

数据记录行/文档

Column

Field

数据字段/域

index

index

索引

Table joins

 

表连接,MongoDB 不支持

primary key

primary key

主键,MongoDB 自动将 _id 字段设置为主键

 

安装

brew tap mongodb/brew

brew install mongodb-community@4.2

 

安装过程

wangdeMacBook-Pro:~ wang$ brew tap mongodb/brew
Updating Homebrew...
==> Tapping mongodb/brew
Cloning into '/usr/local/Homebrew/Library/Taps/mongodb/homebrew-brew'...
remote: Enumerating objects: 13, done.
remote: Counting objects: 100% (13/13), done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 13 (delta 4), reused 6 (delta 1), pack-reused 0
Unpacking objects: 100% (13/13), done.
Tapped 6 formulae (45 files, 59.7KB).
wangdeMacBook-Pro:~ wang$ brew install mongodb-community@4.2
Updating Homebrew...
==> Installing mongodb-community from mongodb/brew
==> Downloading https://fastdl.mongodb.org/osx/mongodb-macos-x86_64-4.2.1.tgz
######################################################################## 100.0%
==> Caveats
To have launchd start mongodb/brew/mongodb-community now and restart at login:
  brew services start mongodb/brew/mongodb-community
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf
==> Summary
  /usr/local/Cellar/mongodb-community/4.2.1: 21 files, 273.5MB, built in 24 seconds

 

启动

brew services start mongodb/brew/mongodb-community

前台启动
mongod --config /usr/local/etc/mongod.conf

 

查看运行状态

ps aux | grep -v grep | grep mongod

 

连接与使用MongoDB

mongo

 

连接过程

MongoDB shell version v4.2.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b15a0dfa-bfd3-4672-8d76-e5ef38f379e4") }
MongoDB server version: 4.2.1
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
     http://docs.mongodb.org/
Questions? Try the support group
     http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2019-12-09T10:53:59.187+0800 I  CONTROL  [initandlisten] 
2019-12-09T10:53:59.187+0800 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2019-12-09T10:53:59.187+0800 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2019-12-09T10:53:59.187+0800 I  CONTROL  [initandlisten] 
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

>

 

help命令

> help
     db.help()                    help on db methods
     db.mycoll.help()             help on collection methods
     sh.help()                    sharding helpers
     rs.help()                    replica set helpers
     help admin                   administrative help
     help connect                 connecting to a db help
     help keys                    key shortcuts
     help misc                    misc things to know
     help mr                      mapreduce

     show dbs                     show database names
     show collections             show collections in current database
     show users                   show users in current database
     show profile                 show most recent system.profile entries with time >= 1ms
     show logs                    show the accessible logger names
     show log [name]              prints out the last segment of log in memory, 'global' is default
     use <db_name>                set current database
     db.foo.find()                list objects in collection foo
     db.foo.find( { a : 1 } )     list objects in foo where a == 1
     it                           result of the last line evaluated; use to further iterate
     DBQuery.shellBatchSize = x   set default number of items to display on shell
     exit                         quit the mongo shell

 

创建数据库

> use test
switched to db test

 

显示数据库

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

test库没显示,是因为这个库里没有存任何数据。

 

插入一条数据

> db.users.insertOne({name:"sue", age:26,status:"pending"})
{
     "acknowledged" : true,
     "insertedId" : ObjectId("5dedc4b4343c58031d1a4a42")
}

如图:

 

查询数据

> db.users.find({name:"sue"})
{ "_id" : ObjectId("5dedc4b4343c58031d1a4a42"), "name" : "sue", "age" : 26, "status" : "pending" }

 

更新数据

> db.users.updateOne({name:"sue"},{$set:{status:"pending_XXX"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.test.find({name:"sue"})
{ "_id" : ObjectId("5dedc4b4343c58031d1a4a42"), "name" : "sue", "age" : 26, "status" : "pending_XXX" }

 

删除数据

> db.users.deleteOne({name:"sue"})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.test.find({name:"sue"})
>

 

显示数据库中所有的集合(表)

> show collections
users

 

查询集合(表)中所有文档(行)

> db.users.find()
{ "_id" : ObjectId("5dedee8e343c58031d1a4a43"), "name" : "sue", "age" : 26, "status" : "pending_XXX" }

 


 

DEMO

新建一个Spring Boot工程(springBootDemo31),此Demo使用MongoRepository的形式操作MongoDB

pom.xml中引入依赖

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


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

 

application.properties加入配置项

spring.data.mongodb.uri=mongodb://localhost:27017/test

 

新建一个model类,User.java

package com.example.demo.model;


import java.io.Serializable;


public class User implements Serializable
{
    private Long id;
    private String userName;
    private String passWord;


    public Long getId()
    {
        return id;
    }


    public void setId(Long id)
    {
        this.id = id;
    }


    public String getUserName()
    {
        return userName;
    }


    public void setUserName(String userName)
    {
        this.userName = userName;
    }


    public String getPassWord()
    {
        return passWord;
    }


    public void setPassWord(String passWord)
    {
        this.passWord = passWord;
    }


    @Override
    public String toString()
    {
        return "User{id=" + id + ", userName='" + userName + "', passWord='" + passWord + "'}";
    }
}

 

新建一个Repository类,UserRepository.java

package com.example.demo.repository;


import com.example.demo.model.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;


import java.util.Optional;


public interface UserRepository extends MongoRepository<User, Long>
{
    Optional<User> findById(Long Id);


    User findByUserName(String userName);


    Page<User> findAll(Pageable var1);
}

 

接下来就可以开始测试了

package com.example.demo;


import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;


import java.util.Optional;


@SpringBootTest
public class RepositoryTest
{
    @Autowired
    private UserRepository userRepository;


    @Test
    public void testSaveUser() throws Exception
    {
        for (long i = 0; i < 30; i++)
        {
            User user = new User();
            user.setId(i);
            user.setUserName("小明" + i);
            user.setPassWord("123456");
            userRepository.save(user);
        }
    }


    @Test
    public void findUserById()
    {
        Optional<User> obj = userRepository.findById(2L);
        User user = obj.get();
        System.out.println("user is " + user);
    }


    @Test
    public void findUserByUserName()
    {
        User user = userRepository.findByUserName("小明1");
        System.out.println("user is " + user);
    }


    @Test
    public void updateUser()
    {
        User user = new User();
        user.setId(2l);
        user.setUserName("小明XXX");
        user.setPassWord("88888888");
        userRepository.save(user);
    }


    @Test
    public void deleteUserById()
    {
        userRepository.deleteById(2l);
    }


    @Test
    public void testPage()
    {
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(1, 10, sort);
        Page page = userRepository.findAll(pageable);
        for(Object user : page.getContent())
        {
            System.out.println(user);
        }
    }
}

 

测试testSaveUser()

> show collections
user
> db.user.find()
{ "_id" : NumberLong(0), "userName" : "小明0", "passWord" : "123456" }
{ "_id" : NumberLong(1), "userName" : "小明1", "passWord" : "123456" }
{ "_id" : NumberLong(2), "userName" : "小明2", "passWord" : "123456" }
{ "_id" : NumberLong(3), "userName" : "小明3", "passWord" : "123456" }
{ "_id" : NumberLong(4), "userName" : "小明4", "passWord" : "123456" }
{ "_id" : NumberLong(5), "userName" : "小明5", "passWord" : "123456" }
{ "_id" : NumberLong(6), "userName" : "小明6", "passWord" : "123456" }
{ "_id" : NumberLong(7), "userName" : "小明7", "passWord" : "123456" }
{ "_id" : NumberLong(8), "userName" : "小明8", "passWord" : "123456" }
{ "_id" : NumberLong(9), "userName" : "小明9", "passWord" : "123456" }
{ "_id" : NumberLong(10), "userName" : "小明10", "passWord" : "123456" }
{ "_id" : NumberLong(11), "userName" : "小明11", "passWord" : "123456" }
{ "_id" : NumberLong(12), "userName" : "小明12", "passWord" : "123456" }
{ "_id" : NumberLong(13), "userName" : "小明13", "passWord" : "123456" }
{ "_id" : NumberLong(14), "userName" : "小明14", "passWord" : "123456" }
{ "_id" : NumberLong(15), "userName" : "小明15", "passWord" : "123456" }
{ "_id" : NumberLong(16), "userName" : "小明16", "passWord" : "123456" }
{ "_id" : NumberLong(17), "userName" : "小明17", "passWord" : "123456" }
{ "_id" : NumberLong(18), "userName" : "小明18", "passWord" : "123456" }
{ "_id" : NumberLong(19), "userName" : "小明19", "passWord" : "123456" }
Type "it" for more
>

 

测试findUserByUserName()

user is User{id=1, userName='小明1', passWord='123456'}

 

测试updateUser()

> db.user.findOne({"_id" : NumberLong(2)})
{
     "_id" : NumberLong(2),
     "userName" : "小明XXX",
     "passWord" : "88888888",
     "_class" : "com.example.demo.model.User"
}

 

测试deleteUserById()

> db.user.findOne({"_id" : NumberLong(2)})
null

 

测试testPage()

User{id=11, userName='小明11', passWord='123456'}
User{id=12, userName='小明12', passWord='123456'}
User{id=13, userName='小明13', passWord='123456'}
User{id=14, userName='小明14', passWord='123456'}
User{id=15, userName='小明15', passWord='123456'}
User{id=16, userName='小明16', passWord='123456'}
User{id=17, userName='小明17', passWord='123456'}
User{id=18, userName='小明18', passWord='123456'}
User{id=19, userName='小明19', passWord='123456'}
User{id=20, userName='小明20', passWord='123456'}

 


DEMO2

新建一个Spring Boot工程(springBootDemo31B),此Demo使用MongoTemplate的形式操作MongoDB

 

pom.xml加入依赖

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


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

 

application.properties

spring.data.mongodb.uri=mongodb://localhost:27017/test

 

MongoConfig.java

package com.example.demo.config;


import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;


@Configuration
public class MongoConfig
{
    @Value("${spring.data.mongodb.uri}")
    private String mongodbUri;


    @Primary
    @Bean(name = "mongoTemplate")
    public MongoTemplate mongoTemplate() throws Exception
    {
        MappingMongoConverter converter = new MappingMongoConverter(new DefaultDbRefResolver(mongoFactory()), new MongoMappingContext());
        converter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(mongoFactory(), converter);
    }


    @Primary
    @Bean
    public MongoDbFactory mongoFactory() throws Exception
    {
        MongoClient client = new MongoClient(new MongoClientURI(mongodbUri));
        return new SimpleMongoDbFactory(client, "test");
    }
}

 

Model类,User.java

package com.example.demo.model;

import java.io.Serializable;


public class User implements Serializable
{
    private Long id;
    private String userName;
    private String passWord;

    public Long getId()
    {
        return id;
    }

    public void setId(Long id)
    {
        this.id = id;
    }

    public String getUserName()
    {
        return userName;
    }
    
    public void setUserName(String userName)
    {
        this.userName = userName;
    }
    
    public String getPassWord()
    {
        return passWord;
    }

    public void setPassWord(String passWord)
    {
        this.passWord = passWord;
    }

    @Override
    public String toString()
    {
        return "User{id=" + id + ", userName='" + userName + "', passWord='" + passWord + "'}";
    }
}

 

Repository类,UserRepository.java

package com.example.demo.repository;


import com.example.demo.model.User;


public interface UserRepository
{
    public void saveUser(User user);


    public User findUserByUserName(String userName);


    public long updateUser(User user);


    public void deleteUserById(Long id);
}

 

实现接口UserRepositoryImpl.java

package com.example.demo.repository.impl;


import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;


@Component
public class UserRepositoryImpl implements UserRepository
{
    private MongoTemplate mongoTemplate;


    @Autowired
    public void setRabbitTemplate(MongoTemplate mongoTemplate)
    {
        this.mongoTemplate = mongoTemplate;
    }


    /**
     * 创建对象
     *
     * @param user
     */
    @Override
    public void saveUser(User user)
    {
        mongoTemplate.save(user);
    }


    /**
     * 根据用户名查询对象
     *
     * @param userName
     * @return
     */
    @Override
    public User findUserByUserName(String userName)
    {
        Query query = new Query(Criteria.where("userName").is(userName));
        User user = mongoTemplate.findOne(query, User.class);
        return user;
    }


    /**
     * 更新对象
     *
     * @param user
     */
    @Override
    public long updateUser(User user)
    {
        Query query = new Query(Criteria.where("id").is(user.getId()));
        Update update = new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, User.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        if (result != null)
        {
            return result.getMatchedCount();
        }
        else
        {
            return 0;
        }
    }


    /**
     * 删除对象
     *
     * @param id
     */
    @Override
    public void deleteUserById(Long id)
    {
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, User.class);
    }
}

 

开始测试

package com.example.demo;


import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
public class UserTemplateTest
{
    @Autowired
    private UserRepository userRepository;


    @Test
    public void testSaveUser() throws Exception
    {
        User user = new User();
        user.setId(2l);
        user.setUserName("小明");
        user.setPassWord("12345678");
        userRepository.saveUser(user);
    }


    @Test
    public void findUserByUserName()
    {
        User user = userRepository.findUserByUserName("小明");
        System.out.println("user is " + user);
    }


    @Test
    public void updateUser()
    {
        User user = new User();
        user.setId(2l);
        user.setUserName("天空");
        user.setPassWord("888888");
        userRepository.updateUser(user);
    }


    @Test
    public void deleteUserById()
    {
        userRepository.deleteUserById(2L);
    }
}

 

测试之前先执行命令删除当前集合(表)

> db.user.drop()
true
> show collections
>

 

testSaveUser()

> db.user.find()
{ "_id" : NumberLong(2), "userName" : "小明", "passWord" : "12345678" }

 

findUserByUserName()

user is User{id=2, userName='小明', passWord='12345678'}

 

updateUser()

> db.user.find()
{ "_id" : NumberLong(2), "userName" : "天空", "passWord" : "888888" }

 

deleteUserById()

> db.user.find()
>

 


DEMO3

新建一个Spring Boot工程(springBootDemo31C),此Demo使用MongoRepository的形式,通过自定义数据源的方法,实现多数据源访问操作MongoDB。

pom.xml加入依赖

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


   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
      <exclusions>
         <exclusion>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
         </exclusion>
      </exclusions>
   </dependency>
</dependencies>

 

application.properties

mongodb.primary.uri=mongodb://localhost:27017
mongodb.primary.database=primary
mongodb.secondary.uri=mongodb://localhost:27017
mongodb.secondary.database=secondary

 

新建一个Properties类,名称MultipleMongoProperties,用来加载自定义的配置项。

package com.example.demo.config.props;


import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;


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


    public MongoProperties getPrimary()
    {
        return primary;
    }


    public void setPrimary(MongoProperties primary)
    {
        this.primary = primary;
    }


    public MongoProperties getSecondary()
    {
        return secondary;
    }


    public void setSecondary(MongoProperties secondary)
    {
        this.secondary = secondary;
    }
}

 

有了Properties类之后,接下来就可以新建一个配置类MultipleMongoConfig,通过使用上一步获取的配置信息构建MongoDbFactory继而构建MongoTemplate。

package com.example.demo.config;


import com.example.demo.config.props.MultipleMongoProperties;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;


@Configuration
public class MultipleMongoConfig
{
    private MultipleMongoProperties mongoProperties;


    @Autowired
    public void setMongoProperties(MultipleMongoProperties mongoProperties)
    {
        this.mongoProperties = mongoProperties;
    }


    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate() throws Exception
    {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }


    @Qualifier("secondaryMongoTemplate")
    @Bean
    public MongoTemplate secondaryMongoTemplate() throws Exception
    {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }


    @Primary
    @Bean
    public MongoDbFactory primaryFactory(MongoProperties mongo) throws Exception
    {
        MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getPrimary().getUri()));
        return new SimpleMongoDbFactory(client, mongoProperties.getPrimary().getDatabase());
    }


    @Bean
    public MongoDbFactory secondaryFactory(MongoProperties mongo) throws Exception
    {
        MongoClient client = new MongoClient(new MongoClientURI(mongoProperties.getSecondary().getUri()));
        return new SimpleMongoDbFactory(client, mongoProperties.getSecondary().getDatabase());
    }
}

 

接下来就是定义Repository环节。

PrimaryRepository

package com.example.demo.repository.primary;


import com.example.demo.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;


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

 

SecondaryRepository

package com.example.demo.repository.secondary;


import com.example.demo.model.User;
import org.springframework.data.mongodb.repository.MongoRepository;


public interface SecondaryRepository extends MongoRepository<User, String>
{
}

 

按照往常的理解,有了自定义Repository之后就可以用来操作数据库了。但是这里不行,因为我们使用了自定义数据源配置,因此这里还需要手工指定Repository使用的MongoTemplate。

PrimaryMongoConfig
 

package com.example.demo.config;


import com.example.demo.config.props.MultipleMongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;


@Configuration
@EnableConfigurationProperties(MultipleMongoProperties.class)
@EnableMongoRepositories(basePackages = "com.example.demo.repository.primary", mongoTemplateRef = "primaryMongoTemplate")
public class PrimaryMongoConfig
{
}

 

SecondaryMongoConfig

package com.example.demo.config;


import com.example.demo.config.props.MultipleMongoProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;


@Configuration
@EnableConfigurationProperties(MultipleMongoProperties.class)
@EnableMongoRepositories(basePackages = "com.example.demo.repository.secondary", mongoTemplateRef = "secondaryMongoTemplate")
public class SecondaryMongoConfig
{
}

 

接下来就可以开始测试了

package com.example.demo;


import com.example.demo.model.User;
import com.example.demo.repository.primary.PrimaryRepository;
import com.example.demo.repository.secondary.SecondaryRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


import java.util.List;


@SpringBootTest
public class MuliDatabaseTest
{
    private PrimaryRepository primaryRepository;
    @Autowired
    public void setPrimaryRepository(PrimaryRepository primaryRepository)
    {
        this.primaryRepository = primaryRepository;
    }


    private SecondaryRepository secondaryRepository;
    @Autowired
    public void setSecondaryRepository(SecondaryRepository secondaryRepository)
    {
        this.secondaryRepository = secondaryRepository;
    }


    @Test
    public void TestSave()
    {
        System.out.println("测试开始");


        // 保存数据
        this.primaryRepository.save(new User(1L, "小张", "123456"));
        this.secondaryRepository.save(new User(2L, "小王", "111111"));


        // 查询数据
        List<User> primaries = this.primaryRepository.findAll();
        for (User primary : primaries)
        {
            System.out.println(primary.toString());
        }


        // 查询数据
        List<User> secondaries = this.secondaryRepository.findAll();
        for (User secondary : secondaries)
        {
            System.out.println(secondary.toString());
        }
        System.out.println("测试完成");
    }
}

 

控制台输出

测试开始
2019-12-12 16:56:44.148  INFO 92884 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:3, serverValue:58}] to localhost:27017
2019-12-12 16:56:44.244  INFO 92884 --- [           main] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:4, serverValue:59}] to localhost:27017
User{id=1, userName='小张', passWord='123456'}
User{id=2, userName='小王', passWord='111111'}
测试完成

 

终端工具查询

> use primary
switched to db primary
> show collections
user
> db.user.find()
{ "_id" : NumberLong(1), "userName" : "小张", "passWord" : "123456", "_class" : "com.example.demo.model.User" }
> use secondary
switched to db secondary
> show collections
user
> db.user.find()
{ "_id" : NumberLong(2), "userName" : "小王", "passWord" : "111111", "_class" : "com.example.demo.model.User" }

 

参考文档:

https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/

 

Bootstrap Thumbnail Second
MySQL

MySQL is the world's most popular open source database.

GO

Bootstrap Thumbnail Third
算法基础

本书介绍了什么是计算机算法,如何描述它们,以及如何来评估它们。

GO