Spring Data MongoDB - Hello World Example

In this tutorial, we will show how to configure MongoDB using Spring Data. And then we will create hello world example to show how to perform CRUD operations with MongoDB and Spring Data. 

In order to run this example, you would need to install mongodb and follow the instructions and would need to have following tools and libraries.

  • JDK/Java 1.6 or later
  • Eclipse 3.6 or later
  • spring-data-mongodb-1.0.2.RELEASE (download it from here)
  • spring-data-commons-core-1.2.0.RELEASE (download it from here)
  • java mongodb driver 2.10.1 (dowload it from here)
  • spring-core-3.1.1.RELEASE
  • spring-context-3.1.1.RELEASE
  • spring-asm-3.1.1.RELEASE
  • spring-expression-3.1.1.RELEASE
  • spring-aop-3.1.1.RELEASE
  • spring-tx-3.1.1.RELEASE
  • cglib-nodep-2.1.3
Spring Configuration File (spring-config.xml)

 This spring configuration file contains related bean configurations in order to run this example. Please make sure that this file is in the classpath.

<?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"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">
        
    <context:annotation-config/>
    
    <context:component-scan base-package="com.mycompany.mongodb">
     <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/>
    </context:component-scan>
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
     <constructor-arg name="mongo" ref="mongo"/>
     <constructor-arg name="databaseName" value="test"/>
     </bean>

 <!-- Factory bean that creates the Mongo instance -->
    <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean">
     <property name="host" value="localhost"/>
    </bean>
    
 <!-- Use this post processor to translate any MongoExceptions thrown in @Repository annotated classes -->
 <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
    
</beans>



Domain Objects or Classes
   
   Account.java and Person.java represent domain classes which spring data will use to convert them from/to mongodb representation.

Account.java

package com.mycompany.mongodb.domain;

public class Account {

 public enum Type {
  SAVINGS, CHECKING
 }

 private String id;

 private String accountNumber;

 private Account.Type accountType;

 private Double balance;

 public Account(){
 }

 public Account(String accountNumber, Type accountType, Double balance) {
  super();
  this.accountNumber = accountNumber;
  this.accountType = accountType;
  this.balance = balance;
 }

 public String getId() {
  return id;
 }

 public void setId(String id) {
  this.id = id;
 }

 public String getAccountNumber() {
  return accountNumber;
 }

 public void setAccountNumber(String accountNumber) {
  this.accountNumber = accountNumber;
 }

 public Account.Type getAccountType() {
  return accountType;
 }

 public void setAccountType(Account.Type accountType) {
  this.accountType = accountType;
 }

 public Double getBalance() {
  return balance;
 }

 public void setBalance(Double balance) {
  this.balance = balance;
 }

 @Override
 public String toString() {
  return "Account [id=" + id + ", accountNumber=" + accountNumber
    + ", accountType=" + accountType + ", balance=" + balance + "]";
 }

}


Person.java 


package com.mycompany.mongodb.domain;

import java.util.ArrayList;
import java.util.List;

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

@Document
public class Person {

 @Id
 private String id;

 private String name;

 private int age;

 private List<Account> accounts = new ArrayList<Account>();

 public Person() {
 }

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

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

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public List<Account> getAccounts() {
  return accounts;
 }

 public void addAccount(Account account) {
  this.accounts.add(account);
 }

 public void setAccounts(List<Account> accounts) {
  this.accounts = accounts;
 }

 @Override
 public String toString() {
  return "Person [id=" + id + ", name=" + name + ", age=" + age
    + ", accounts=" + accounts + "]";
 }

}


HelloMongo.java

 This class will perform CRUD operations on Account and Person objects and show you the demo.

package com.mycompany.mongodb;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;

import org.springframework.stereotype.Repository;

import com.mycompany.mongodb.domain.Account;
import com.mycompany.mongodb.domain.Person;

@Repository
public class HelloMongo {

 @Autowired
 MongoOperations mongoOperations;

 public void run() {

  if (mongoOperations.collectionExists(Person.class)) {
   mongoOperations.dropCollection(Person.class);
  }

  mongoOperations.createCollection(Person.class);

  Person p = new Person("John", 39);
  Account a = new Account("1234-59873-893-1", Account.Type.SAVINGS, 123.45D);
  p.getAccounts().add(a);

  mongoOperations.insert(p);

  List<Person> results = mongoOperations.findAll(Person.class);
  System.out.println("Results: " + results);
 }

}


Running the Example

 Following code shows how to run this example

package com.mycompany.mongodb;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Hello Mongo!
 */
public class App 
{
 public static void main( String[] args ) {
       ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        HelloMongo hello = context.getBean(HelloMongo.class);
        hello.run();
        System.out.println( "DONE!" );
 }
}


And here you go. You would see following output once you run this.

Results: [Person [id=50d0043fa8ca9e8996923a08, name=John, age=39, accounts=[Account [id=null, accountNumber=1234-59873-893-1, accountType=SAVINGS, balance=123.45]]]]
DONE!






2 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Should you have a run method if it's not in a runnable as this would cause confusion.

    ReplyDelete