mbird mbird - 28 days ago 14
Java Question

Spring Data : Java configuration for MongoDB without XML

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.

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?

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 :)

Answer

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