Spring Data:没有 XML 的 MongoDB 的 Java 配置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23527506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:36:29  来源:igfitidea点击:

Spring Data : Java configuration for MongoDB without XML

javaspringmongodbspring-dataspring-data-mongodb

提问by mbird

I tried the Spring Guide Accessing Data with MongoDB. What I can't figure out is how do I configure my code to not use the default server address and not use the default database. I have seen many ways to do it with XML but I am trying to stay with fully XML-less configurations.

我尝试了Spring Guide Accessing Data with MongoDB。我无法弄清楚的是如何配置我的代码以不使用默认服务器地址和不使用默认数据库。我已经看到了很多使用 XML 来实现它的方法,但我正在尝试使用完全无 XML 的配置。

Does anyone have an example that sets the server and database without XML and can be easily integrated into the sample they show in the Spring Guide?

有没有人有一个示例,可以在没有 XML 的情况下设置服务器和数据库,并且可以轻松集成到他们在 Spring Guide 中显示的示例中?

Note: I did find how to set the collection (search for the phrase "Which collection will my documents be saved into " on this page.

注意:我确实找到了如何设置集合(在此页面上搜索短语“我的文档将保存到哪个集合中” 。

Thank you!

谢谢!

p.s. same story with the Spring Guide for JPA -- how do you configure the db properties -- but that is another post :)

ps 与 Spring Guide for JPA 相同的故事——你如何配置 db 属性——但那是另一篇文章:)

采纳答案by Jean-Philippe Bond

It would be something like this for a basic configuration :

对于基本配置,它会是这样的:

@Configuration
@EnableMongoRepositories
public class MongoConfiguration extends AbstractMongoConfiguration {

    @Override
    protected String getDatabaseName() {
        return "dataBaseName";
    }

    @Override
    public Mongo mongo() throws Exception {
        return new MongoClient("127.0.0.1", 27017);
    }

    @Override
    protected String getMappingBasePackage() {
        return "foo.bar.domain";
    }
}

Example for a document :

文档示例:

@Document
public class Person {

    @Id
    private String id;

    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Example for a repository :

存储库示例:

@Repository
public class PersonRepository {

    @Autowired
    MongoTemplate mongoTemplate;

    public long countAllPersons() {
        return mongoTemplate.count(null, Person.class);
    }
}