Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 631
Matt M. Avatar asked May 07 '14 20:05

Matt M.


People also ask

Can we use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases.

What is @document annotation in spring boot?

@Document is an annotation provided by Spring data project. It is used to identify a domain object, which is persisted to MongoDB. So you can use it to map a Java class into a collection inside MongoDB. If you don't use Spring Data, you don't need this annotation.


1 Answers

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);
    }
}
like image 106
Jean-Philippe Bond Avatar answered Oct 02 '22 13:10

Jean-Philippe Bond