Spring:单个实体中的 2 个存储库 [英] Spring: 2 Repositories out of a single Entity

查看:13
本文介绍了Spring:单个实体中的 2 个存储库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要的是从单个实体创建的 2 个存储库:

What I need is 2 Repositories created out of a single entity:

interface TopicRepository implements ReactiveCrudRepository<Topic, String>

interface BackupTopicRepository implements ReactiveCrudRepository<Topic, String>

这怎么可能?现在只创建了一个.

How is that possible? Right now only one is created.

推荐答案

这就是你要做的.

@Configuration
@ConfigurationProperties(prefix = "mongodb.topic")
@EnableMongoRepositories(basePackages = "abc.def.repository.topic", mongoTemplateRef = "topicMongoTemplate")
@Setter
class TopicMongoConfig {

    private String host;
    private int port;
    private String database;

    @Primary
    @Bean(name = "topicMongoTemplate")
    public MongoTemplate topicMongoTemplate() throws Exception {
        final Mongo mongoClient = createMongoClient(new ServerAddress(host, port));
        return new MongoTemplate(mongoClient, database);
    }

     private Mongo createMongoClient(ServerAddress serverAddress) {
        return new MongoClient(serverAddress);
    }
}

另一种配置

@Configuration
@ConfigurationProperties(prefix = "mongodb.backuptopic")
@EnableMongoRepositories(basePackages = "abc.def.repository.backuptopic", mongoTemplateRef = "backupTopicMongoTemplate")
@Setter
class BackupTopicMongoConfig {

    private String host;
    private int port;
    private String database;

    @Primary
    @Bean(name = "backupTopicMongoTemplate")
    public MongoTemplate backupTopicMongoTemplate() throws Exception {
        final Mongo mongoClient = createMongoClient(new ServerAddress(host, port));
        return new MongoTemplate(mongoClient, database);
    }

     private Mongo createMongoClient(ServerAddress serverAddress) {
        return new MongoClient(serverAddress);
    }
}

您的 TopicRepository 和 BackuoTopicRepository 应分别位于 abc.def.repository.topic 和 abc.def.repository.backuptopic 中.

Your TopicRepository and BackuoTopicRepository should reside in abc.def.repository.topic and abc.def.repository.backuptopic respectively.

您还需要在属性或 yml 文件中定义这些属性

And also you need to have these properties defined in your properties or yml file

mongodb: 
   topic:
     host:
     database:
     port:
   backuptopic:
     host:
     database:
     port:

最后,禁用 mongo 的 springboot 自动配置.

Lastly, disable springboot autoconfiguration for mongo.

@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

这篇关于Spring:单个实体中的 2 个存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆