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

查看:67
本文介绍了春季:单个实体中有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.

推荐答案

这就是您要执行的操作.

This is how you would do it.

@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})

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

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