Setting up a project with Spring Data and MongoDB
From springsource : “The goal of the Spring Data Document (or DATADOC) framework is to provide an extension to the Spring programming model that supports writing applications that use Document databases”.
This blog will cover on how to use Spring Data with MongoDB. We will start with creating a simple Spring MVC application. See my previous blog to see how to setup a basic Spring MVC app using STS.
We will first add the dependencies on the pom file of the project.
<!-- Spring Data Mongo Driver --> <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.1.0.M1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2</version> </dependency>
We will also need to add the Spring Milestone repo to the pom
<repositories> <repository> <id>spring-milestone</id> <name>Spring Maven MILESTONE Repository</name> <url>http://maven.springframework.org/milestone</url> </repository> </repositories>
CONFIGURING MONGO TEMPLATE USING SPRING XML
We will now create a mongo-config.xml in the WEB-INF directory of the project. Add this as the content of the 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.1.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.1.xsd"> <!-- Default bean name is 'mongo' --> <mongo:mongo host="localhost" port="27017" /> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongo" /> <constructor-arg name="databaseName" value="codesilo" /> </bean> <!-- To translate any MongoExceptions thrown in @Repository annotated classes --> <context:annotation-config /> </beans>
Add this to the web.xml configLocation
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml /WEB-INF/mongo-config.xml </param-value> </context-param>
We will keep things simple. Create a user model and refactor the homeController class to use that model. The HomeController class will create a User object, insert it in the database, query and return the first result to the view.
The following is the model User class.
public class User { public String username; public String password; public String firstName; public String lastName; public User(){ } public User(String username, String password, String firstName, String lastName){ this.username = username; this.password = password; this.firstName = firstName; this.lastName = lastName; } 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 String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString(){ return "User [username=" + username + ", passowrd= ****" + ", firstName=" + firstName + "lastName" + lastName + "]"; } }
Change the HomeController class to look like the following
@Controller public class HomeController { @Autowired private MongoTemplate mongoTemplate; private static final Logger logger = LoggerFactory.getLogger(HomeController.class); /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! the client locale is "+ locale.toString()); MongoOperations mongoOperation = (MongoOperations)mongoTemplate; User user = new User("codesilo", "Password", "Code", "Silo"); mongoOperation.save(user); List<User> users = mongoOperation.find( new Query(Criteria.where("username").is("codesilo")), User.class); model.addAttribute("user", users.get(0).toString()); return "home"; } }
Change the body of home.jsp to the following
<body> <h1> Hello world! </h1> <P> Getting user from MongoDB: ${user} </P> </body>
Now when we go to the application, we will see the following
and when we use the mongo shell to query the database, we get..
> db.user.find(); { "_id" : ObjectId("4fef96227e27ff2b7a81331f"), "_class" : "com.wordpress.codesilo.model.User", "username" : "codesilo", "password" : "Password", "firstName" : "Code", "lastName" : "Silo" }
References:
MongoTemplate- SpringSource Documentation
Great example, but I believe that final mongo shell query shouldn’t be pluralized, i.e.:
db.user.find()
…since the collection is named after the User class (not Users).
Nice catch Ryan. Thanks. I have corrected the query.
HI,
mongo-config.xml not working in my project it gives below error:
org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘mongoTemplate’ defined in ServletContext resource [/WEB-INF/mongo-config.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.data.mongodb.core.MongoTemplate]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/objenesis/ObjenesisStd
Please help me
Could be because of the version of Mongo you are trying to use. See the resolution of a similar issue here http://stackoverflow.com/questions/25262248/missing-class-org-springframework-objenesis-objenesisstd