MongoDb with Spring Data

Using spring-data to access MongoDB in Java is quite interesting since the primary goal of Spring Data project is to make it easier to use and it does 🙂

Maven configuration.

That’s the configuration that I used for this simple sample. Notice that I used maven-assembly-plugin do create a fat jar and execute it as a standalone app, may you prefer using something fancy like Spring Boot.

<?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>java4.fun.data</groupId>
   <artifactId>oracle-to-mongo</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <version>1.16.6</version>
      </dependency>

      <!-- Spring -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>4.2.4.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>4.1.6.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aop</artifactId>
         <version>4.2.4.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.springframework.data</groupId>
         <artifactId>spring-data-mongodb</artifactId>
         <version>1.9.6.RELEASE</version>
      </dependency>
      <dependency>
         <groupId>org.mongodb</groupId>
         <artifactId>mongodb-driver</artifactId>
         <version>3.4.1</version>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
         <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
               <archive>
                  <manifest>
                     <mainClass>java4.fun.data.Main</mainClass>
                  </manifest>
               </archive>
               <descriptorRefs>
                  <descriptorRef>jar-with-dependencies</descriptorRef>
               </descriptorRefs>
            </configuration>
            <executions>
               <execution>
                  <id>make-assembly</id>
                  <phase>package</phase>
                  <goals>
                     <goal>single</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>
</project>

 

Spring configuration

Next, let’s create the files that will compose the spring configurations, in this case, let’s create them into “src/main/resources”.

application.properties

mongodb.host=localhost
mongodb.host.port=27017
mongodb.database=technicalanalyzer

applicationContext.xml

<?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:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation=
             "http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/data/mongo
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd
          http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <context:property-placeholder location="classpath*:application.properties"/>

   <mongo:mongo id="mongo" host="${mongodb.host}" port="${mongodb.host.port}"/>
   <mongo:repositories base-package="java4.fun.data.mongo.repository" />

   <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
      <constructor-arg ref="mongo" />
      <constructor-arg name="databaseName" value="${mongodb.database}" />
   </bean>

   <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

   <context:annotation-config />
   <context:component-scan base-package="java4.fun.data"/>

</beans>

 

Model

Now a really simple model with just an Id and a Title.

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Data
@Document(collection="ArticleEntity")
public class ArticleEntity {
   @Id
   private long articleId;
   private String title;
}

OBS : @Data is a Lombook annotation.

 

Spring Service

import java4.fun.data.mongo.entity.ArticleEntity;
import java4.fun.data.mongo.repository.MongoArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MongoArticleService {

   private final MongoArticleRepository repository;

   @Autowired
   public MongoArticleService(final MongoArticleRepository repository) {
      this.repository = repository;
   }

   public ArticleEntity save(ArticleEntity article) {
      return repository.save(article);
   }
}

 

Spring Repository

This is a good one, since Spring offers default implementations for CrudRepository like SimpleMongoRepository to perform basic operations (even those not so basic), it’s not necessary to write anything, just create an interface that extends CrudRepository.

import java4.fun.data.mongo.entity.ArticleEntity;
import org.springframework.data.repository.CrudRepository;

public interface MongoArticleRepository extends CrudRepository<ArticleEntity, Long> {
}

That’s it, this is our CRUD.

 

Main

import java4.fun.data.mongo.entity.ArticleEntity;
import java4.fun.data.mongo.service.MongoArticleService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import java.util.logging.Level;
import java.util.logging.Logger;

public class Main {

   private static final Logger LOG = Logger.getLogger(Main.class.getName());
   private static final int OK = 0;
   private static final int NOK = 1;

   public static void main(String... args) throws ClassNotFoundException {
      final ApplicationContext ctx = new GenericXmlApplicationContext("applicationContext.xml");

      try {

         final MongoArticleService mongoArticleService = ctx.getBean(MongoArticleService.class);

         final ArticleEntity articleEntity = getDummyArticleEntity();
         mongoArticleService.save(articleEntity);

      } catch (Exception e) {
         LOG.log(Level.SEVERE, e.getMessage());
         System.exit(NOK);
      }

      System.exit(OK);
   }

   private static ArticleEntity getDummyArticleEntity() {
      final ArticleEntity articleEntity = new ArticleEntity();
      articleEntity.setTitle("Spring!");
      return articleEntity;
   }
}

Observe that I’m just saving here but you can try any other operations available. If you want to learn more and try something else you can check the documentation.

the User Guide

the JavaDocs

the home page of Spring Data MongoDB

Allan de Queiroz

Allan de Queiroz
London based software engineer

XServer forward from Linux text mode for Headless purposes.

Hello, this post is about XServer forward from Linux text mode, **not ssh forward, anything related to VNC** or things like that.Recently...… Continue reading