Spring Data MongoDB Application

Let’s create a mongo db application with spring data to do some simple operations.


Firs of all we need to create the pom.xml.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.spring.mongodb</groupId>
    <artifactId>example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <javax.validation.version>1.1.0.Final</javax.validation.version>
        <hibernate.validator.version>5.2.4.Final</hibernate.validator.version>
        <spring.mongodb.version>1.9.7.RELEASE</spring.mongodb.version>
        <spring.version>4.3.6.RELEASE</spring.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${javax.validation.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${hibernate.validator.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>${spring.mongodb.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <showDeprecation>true</showDeprecation>
                    <showWarnings>true</showWarnings>
                    <fork>true</fork>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

[addToAppearHere]

Not let’s create an application context for the spring and here we will define all configurations related to mongodb. So basically we need to define mongo Db URI, factory and the template.

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.1.xsd
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


    <context:component-scan base-package="com.spring.mongodb.example"/>

    <context:property-placeholder properties-ref="coreModelProps"/>
    <util:properties id="coreModelProps"
                     location="application.properties"/>

    <!--URI for mongo-->
    <bean id="coreMongoURI" class="com.mongodb.MongoURI">
        <constructor-arg name="uri" value="${core.mongo.uri}"/>
    </bean>

    <!--factory for mongo-->
    <bean id="coreMongoFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
        <constructor-arg name="uri" ref="coreMongoURI"/>
    </bean>

    <!--mongotemplate for app-->
    <bean id="coreMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="coreMongoFactory"/>
    </bean>
    <bean class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

[addToAppearHere]

So let’s create the application.propeties file inside the resources folder.

core.mongo.uri=mongodb://127.0.0.1:27017/mongodbexample?maxpoolsize=100&waitqueuemultiple=3&waitqueuetimeoutms=30000&connecttimeoutms=10000&sockettimeoutms0&autoconnectretry=true&slaveok=true&readpreference=secondaryPreferred&safe=true

The next step will be to create the User.java model.

package com.spring.mongodb.example.model;

import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

import java.util.Date;

@Document(collection = User.COLLECTION_NAME)
public class User extends AbstractDomain {

    public static final String COLLECTION_NAME = "user";

    public static final String FIELD_EMAIL_ADDRESS = "emailAddress";
    public static final String FIELD_USER_NAME = "userName";
    public static final String FIELD_PASSWORD = "password";
    public static final String FIELD_CREATE_DATE = "createDate";
    public static final String FIELD_MODIFY_DATE = "modifyDate";
    public static final String FIELD_DELETE_DATE = "deleteDate";

    @Indexed(unique = true)
    @Field(FIELD_EMAIL_ADDRESS)
    private String emailAddress;

    @Indexed(unique = true)
    @Field(FIELD_USER_NAME)
    private String userName;

    @Field(FIELD_PASSWORD)
    private String password;

    @Field(FIELD_CREATE_DATE)
    private Date createDate;

    @Field(FIELD_DELETE_DATE)
    private Date deleteDate = null;

    @Field(FIELD_MODIFY_DATE)
    private Date modifyDate;


    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Date getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Date createDate) {
        this.createDate = createDate;
    }

    public Date getDeleteDate() {
        return deleteDate;
    }

    public void setDeleteDate(Date deleteDate) {
        this.deleteDate = deleteDate;
    }

    public Date getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Date modifyDate) {
        this.modifyDate = modifyDate;
    }

    @Override
    public String toString() {
        return "User{" +
                "emailAddress='" + emailAddress + '\'' +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", createDate=" + createDate +
                ", deleteDate=" + deleteDate +
                ", modifyDate=" + modifyDate +
                '}';
    }
}

[addToAppearHere]

After this we need to create the AbstractDao.java

package com.spring.mongodb.example.dao;

import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;

public abstract class AbstractDAO {

    /**
     * Injection of Spring Mongo template.
     */
    @Qualifier("coreMongoTemplate")
    @Autowired(required = true)
    protected MongoTemplate mongoTemplate;

    /**
     * @param id the user ObjectId
     * @return the entity
     */
    protected abstract T findById(ObjectId id);
}

And now we need to create the UserDAO.java

package com.spring.mongodb.example.dao;

import com.spring.mongodb.example.model.User;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.List;

@Repository("userDAO")
public class UserDAO extends AbstractDAO {

    /**
     * {@inheritDoc}
     */
    @Override
    public User findById(ObjectId id) {
        return mongoTemplate.findById(id, User.class, User.COLLECTION_NAME);
    }

    /**
     *
     * @param userName the username
     * @param deleteDate the delete date
     * @return the User by username and delete date
     */
    public User findByUserNameAndDeleteDate(String userName, Date deleteDate) {
        return mongoTemplate.findOne(new Query(Criteria.where(User.FIELD_USER_NAME)
                .is(userName).and(User.FIELD_DELETE_DATE)
                .is(deleteDate)), User.class, User.COLLECTION_NAME);
    }

    /**
     *
     * @return the list of users from the database
     */
    public List list() {
        return mongoTemplate.findAll(User.class, User.COLLECTION_NAME);
    }

    /**
     *
     * @return the count of users
     */
    public long count() {
        return mongoTemplate.getCollection(User.COLLECTION_NAME).count();
    }

    /**
     * @param user
     */
    public void save(User user) {
        user.setCreateDate(new Date());
        mongoTemplate.insert(user, User.COLLECTION_NAME);
    }

    /**
     * @param user
     */
    public void update(User user) {
        user.setModifyDate(new Date());
        mongoTemplate.save(user, User.COLLECTION_NAME);
    }


    /**
     * @param user
     */
    public void delete(User user) {
        user.setDeleteDate(new Date());
        mongoTemplate.save(user, User.COLLECTION_NAME);
    }
}
[addToAppearHere]

And finally we need to create the Application.java to be able to run it.

package com.spring.mongodb.example;

import com.spring.mongodb.example.dao.UserDAO;
import com.spring.mongodb.example.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.UUID;

public class Application {

    public static void main(String[] args) {

        //Create a new ClassPathXmlApplicationContext, loading the definitions
        //from the given XML file and automatically refreshing the context
        final ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //Getting the UserDAO bean
        final UserDAO userDAO = UserDAO.class.cast(ctx.getBean("userDAO"));

        // creating the user model
        final User user = new User();
        final String uuid = UUID.randomUUID().toString();
        final String username = "testUsername" + uuid;
        user.setUserName("");
        user.setEmailAddress(uuid + "[email protected]");
        user.setPassword("testEncryptedPassword");

        // saving the user into the database
        userDAO.save(user);

        // update the user
        user.setUserName("updatedUsername");
        userDAO.update(user);

        // delete the user
        userDAO.delete(user);

        // getting all users from the database
        List list = userDAO.list();
        for (User u : list) {
            System.out.println(u);
        }

        //getting the user count
        long count = userDAO.count();
        System.out.println(count);

        //find the user by ID
        User user1 = userDAO.findById(list.get(0).getId());
        System.out.println(user1);

        // find the user by username and delete date
        User byUserNameAndDeleteDate = userDAO.findByUserNameAndDeleteDate(username, null);
        System.out.println(byUserNameAndDeleteDate);

    }
}

You can download the source codes from the github.