Big Data/Analytics Zone is brought to you in partnership with:

Over 25 years experience, specializing in business technology in the areas of web application development and collaborative computing I been working as an architect-developer for applications or product development. I am particularly interested in organizations that use leading technologies such as Android, Springs, Spring-WebFlow, JSP’s, Servlets, XML, Java, Struts, PHP, LDAP, Maven, JUnit and Web Application Servers. I have a very solid background with Java, OOP, Design-Patterns and Multi-Threading. I am also able to interface with all levels of management! My consulting services enable businesses maximize value from their business process initiatives and IT investments leading to improved organizational performance. Our services leverage business knowledge, process excellence, technology expertise and substantial domain experience in chosen industry verticals. Johnathan Mark has posted 7 posts at DZone. You can read more from them at their website. View Full User Profile

How To Use Spring Data with MongoDB and Spring's Java Configuration (JavaConfig) style with Maven, JUnit, Log4J

  • submit to reddit


In this example I am going to show you how to post data to a MongoDB database using Spring Data Mongo in Java using Spring, Spring Java Configuration, Maven and Log4J.

Spring Java Configuration

Let’s take a quick look at the Spring Java Configuration file that the project is going to be using

@ComponentScan(basePackageClasses = {MongoDBApp.class})
public class MongoConfiguration extends AbstractMongoConfiguration
    protected String getDatabaseName() {
        return "demo";

    public Mongo mongo() throws Exception {
        return new Mongo();

    protected String getMappingBasePackage() {
        return "com.johnathanmarksmith.mongodb.example.domain";


As you can see from the above code the trick to all this is to use @EnableMongoRepositories and to extend your class from AbstractMongoConfiguration.

The Person Object

Now we are going to take a look at the object that we are going to be inserting into the database.

    public class Person {

    private String personId;

    private String name;
    private int age;

    public Person(String name, int age) { = name;
        this.age = age;

    public String getPersonId() {
        return personId;

    public void setPersonId(final String personId) {
        this.personId = personId;

    public String getName() {
        return name;

    public void setName(final String name) { = name;

    public int getAge() {
        return age;

    public void setAge(final int age) {
        this.age = age;
    public String toString() {
        return "Person [id=" + personId + ", name=" + name
                + ", age=" + age +  "]";


You see we use the @Document and the @Id.

The Repository

Now its time to see the source code in the repository

public class PersonRepository {

    static final Logger logger = LoggerFactory.getLogger(PersonRepository.class);

    MongoTemplate mongoTemplate;

    public void countUnderAge() {
        List<Person> results = null;

        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria = criteria.and("age").lte(21);

        results = mongoTemplate.find(query, Person.class);"Total number of under age in database: {}", results.size());

     * This will count how many Person Objects I have
    public void countAllPersons() {
        List<Person> results = mongoTemplate.findAll(Person.class);"Total number in database: {}", results.size());

     * This will install a new Person object with my
     * name and random age
    public void insertPersonWithNameJohnathanAndRandomAge() {

        double age = Math.ceil(Math.random() * 100);
        Person p = new Person("Johnathan", (int) age);


     * this will create a {@link Person} collection if the collection does not already exists
    public void createPersonCollection() {
        if (!mongoTemplate.collectionExists(Person.class)) {

     * this will drop the {@link Person} collection if the collection does already exists
    public void dropPersonCollection() {
        if (mongoTemplate.collectionExists(Person.class)) {

The Main Class

Time for the main class now.. are you ready for all this code??

    public static void main(String[] args) {"MongoDemo application");

        ApplicationContext context = new AnnotationConfigApplicationContext(MongoConfiguration.class);

        PersonRepository personRepository = context.getBean(PersonRepository.class);

        // cleanup person collection before insertion

        //create person collection

        for (int i = 0; i < 10000; i++) {

         * Added Under Age Test For someone to see
        personRepository.countUnderAge();"MongoDemo application");

You can see from the above code how easy it is to use Spring Data Mongo to post data to a MongoDB.

Download and Run Code

You can checkout the project from github.

git clone
cd spring-mongo-demo
mvn clean package
mvn exec:java

Please keep in mind to be able to run this demo application start your MongoDB instance, Yes you need MongoDB.

If you have any questions or comments please email me at or checkout my web site

For a MongoDB guide see

Thanks, Johnathan Mark Smith

Published at DZone with permission of its author, Johnathan Mark Smith.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)