Spring MVC and MongoDB tutorial


This tutorial (not completed yet) has the goal to show how can be easy to create a new Web application based on Spring and MongoDB.

You can find the code of this small application here:
https://github.com/marco76/mvcMongoExample

The prerequisite is to have MongoDB installed and started.
Spring has a module to import all the necessary for MongoDB:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.1.1.RELEASE</version>
</dependency>

In the servlet-context we configure the connection to the database and we create the template that we will use to interact with it:

 <mongo:mongo id="mongo" host="localhost" port="27017"/>

    <beans:bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <beans:constructor-arg ref="mongo"/>
        <beans:constructor-arg name="databaseName" value="jobfinder"/>
    </beans:bean>

    <mongo:repositories base-package="ch.genidea.mvcMongoExample.repository"/>

Here you can see how simple his our class structure:

Screen Shot 2013-03-29 at 19.35.57.png

We use a Person class to store the data in the database:

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

@Document
public class Person {

    @Id
    private ObjectId id;
    private String username;
    private String password;

    public Person() {
    }

For MongoDB we use the annotation @Document in place of the more traditional @Entity used for traditional databases.

In MainMongo.java you can find an example about how to use the Person class.

public class MainMongo {

    private static final Logger log = LoggerFactory.getLogger(MainMongo.class);

    public static void main(String[] args) throws Exception {

        MongoOperations mongoOperations = new MongoTemplate(new Mongo(), &quot;database&quot;);

        mongoOperations.insert(new Person(&quot;marco&quot;, &quot;marco&quot;));

        Person person = mongoOperations.findOne(new Query(Criteria.where(&quot;username&quot;).is(&quot;marco&quot;)), Person.class);

        log.debug(&quot;Person found : &quot; + person.getUsername());

        mongoOperations.dropCollection(&quot;person&quot;);
    }
}

To update the database we can leverage the power of spring data. It’s enough to create an interface that extends CrudRepository to have basic db features magically available:

import ch.genidea.mvcMongoExample.model.Person;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

public interface PersonRepository extends CrudRepository&lt;Person, Long&gt; {
    List&lt;Person&gt; findByUsername(String username);
}

The interface is used in our HomeController to retrieve the list of people records in the database:

 @Autowired
    private PersonRepository personRepository;

    /**
     * Home page renderer
     */
    @RequestMapping(value = &quot;/&quot;, method = RequestMethod.GET)
    public String home(Locale locale, Model model) {

        logger.info(&quot;Home page&quot;);

        Iterable&lt;Person&gt; personList = personRepository.findAll();

        model.addAttribute(&quot;personList&quot;, personList);

        return &quot;home&quot;;
    }

Here the result:

Screen Shot 2013-03-29 at 19.47.23.png

Alternatively we can use MongoTemplate as in the MainMongo class or in the PersonController where we mix MongoTemplate and CrudRepository just to show the possibilities that Spring give to the developer:

We have a very poor page that allows to add a new Person:
Screen Shot 2013-03-29 at 20.20.43.png

when the user click on ‘Save’ the method addPerson is called:

@Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    PersonRepository personRepository;

    @RequestMapping(value = &quot;/savePerson&quot;, method = RequestMethod.POST)
    public String addPerson(@ModelAttribute(&quot;person&quot;) Person person, BindingResult result) {

        List personList = personRepository.findByUsername(person.getUsername());

        if (personList.size() &gt; 0) {
            System.out.println(&quot;Error username already exists&quot;);
        } else {
            System.out.println(&quot;Ok: new username&quot;);
            mongoTemplate.save(person);
        }

        return &quot;redirect:/&quot;;
    }
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s