如何为Spring数据中的类配置MongoDb集合名称

Dan*_*ish 24 java spring mongodb spring-data spring-data-mongodb

我有一个Products在我的MongoDB数据库中调用的集合,它由IProductPrice我的Java代码中的接口表示.以下存储库声明会导致Spring Date查看该集合db.collection: Intelliprice.iProductPrice.

我希望它将其配置为db.collection: Intelliprice.Products使用外部配置而不是放置@Collection(..)注释IProductPrice.这可能吗?我怎样才能做到这一点?

public interface ProductsRepository extends
    MongoRepository<IProductPrice, String> {
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*ohm 19

您当前可以实现此目的的唯一方法是@Document使用collection属性来注释您的域类,以定义此类的集合实例的名称应该持久化.

但是,有一个JIRA问题打开,建议添加一个可插入的命名策略来配置类,集合和属性名称以更全局的方式处理.随意评论您的用例并投票.

  • 谢谢,我知道@Document批注,并且可能最终会使用它。我基本上想从实际的类中外部化配置。您链接到的JIRA问题是在谈论一种命名策略,并且仍然建议对自定义名称使用注释。 (2认同)

Jer*_*mie 12

使用上面的Oliver Gierke的答案,处理我需要为一个实体创建多个集合的项目,我想使用spring存储库,并且需要在使用存储库之前指定要使用的实体.

我设法使用此系统按需修改存储库集合名称,它使用SPeL.但是,您一次只能处理1个集合.

域对象

@Document(collection = "#{personRepository.getCollectionName()}")
public class Person{}
Run Code Online (Sandbox Code Playgroud)

默认Spring存储库:

public interface PersonRepository 
     extends MongoRepository<Person, String>, PersonRepositoryCustom{
}
Run Code Online (Sandbox Code Playgroud)

自定义存储库接口:

public interface PersonRepositoryCustom {
    String getCollectionName();

    void setCollectionName(String collectionName);
}
Run Code Online (Sandbox Code Playgroud)

执行:

public class PersonRepositoryImpl implements PersonRepositoryCustom {

    private static String collectionName = "Person";

    @Override
    public String getCollectionName() {
        return collectionName;
    }

    @Override
    public void setCollectionName(String collectionName) {
        this.collectionName = collectionName;
    }
}
Run Code Online (Sandbox Code Playgroud)

要使用它:

@Autowired
PersonRepository personRepository;

public void testRetrievePeopleFrom2SeparateCollectionsWithSpringRepo(){
        List<Person> people = new ArrayList<>();
        personRepository.setCollectionName("collectionA");
        people.addAll(personRepository.findAll());
        personDocumentRepository.setCollectionName("collectionB");
        people.addAll(personRepository.findAll());
        Assert.assertEquals(4, people.size());
}
Run Code Online (Sandbox Code Playgroud)

否则,如果你需要使用配置变量,你可以使用这样的东西吗?资源

@Value("#{systemProperties['pop3.port'] ?: 25}") 
Run Code Online (Sandbox Code Playgroud)


小智 5

有点晚了,但我发现您可以在 spring-boot 中动态设置 mongo 集合名称,直接访问应用程序配置。

@Document(collection = "#{@environment.getProperty('configuration.property.key')}")
public class DomainModel {...}
Run Code Online (Sandbox Code Playgroud)

我怀疑您可以通过这种方式设置任何注释属性。