Table of contents
Fourth, create a new configuration class
1. Configuration class 1 MallPortMongoConfiguration
2. Configuration class 2 RankingsMongoConfiguration
1. Configure application.yml
Configure the uri of two mongodb databases
spring:
data:
mongodb:
mallport:
uri: mongodb://192.168.56.101:27017/mall-port
database: mall-port
logandreport:
uri: mongodb://192.168.56.101:27017/rankings
database: rankings
2. Create entity classes
Create two entity classes EntityOne, EntityTwo.
/**
*
* @author QLZ
* @date 2021/8/24
*/
@Data
@Document(collection = "entityOne")
public class EntityOne{
@Id
private String mongoId;
private String scopIntegration;
}
/**
*
* @author QLZ
* @date 2021/8/24
*/
@Data
@Document(collection = "entityTwo")
public class EntityTwo{
@Id
private String mongoId;
private String scopIntegration;
}
3. Create Repository
Create a Repository that operates two entity classes, and place them under the repository.rankings package and the repository.reward package respectively.
Fourth, create a new configuration class
1. Configuration class 1 MallPortMongoConfiguration
2. Configuration class 2 RankingsMongoConfiguration
The @ConfigurationProperties(prefix = "spring.data.mongodb.mallport") annotation represents which configuration to start with in the configuration file. That is, the configuration in application.yml above.
@EnableMongoRepositories(basePackages = {"repository.reward"},mongoTemplateRef ="mallPortMongoTemplate")
Don't forget this annotation. The basePackages attribute of this annotation indicates the package path of the Repository that you want to operate on the entity class.
The mongoTemplateRef attribute indicates that we should use our own designated mongoTemplate class as the mongoTemplate under the basePackages package path.
In other words, specify a mongoTemplate to operate the Reopsitory under the basePackages path.
If you don't add @EnableMongoRepositories annotation. When starting, an error will be reported saying that the corresponding Repository cannot be found
Or the mongoTemplate cannot be found. Because you don't add @EnableMongoRepositories, the default value of the mongoTemplateRef attribute is mongoTemplate. See the source code below
5. Call
The operation of different databases can be realized by automatically assembling the corresponding Mongotemplate through @Autowired.