Spring provides a module called spring data mongodb which provides a wrapper of mongodb. It simplifies the life of a developer by providing default implementations for CRUD and allowing the developer to write queries and other interactions in a easier way.
What should you do to get started on Spring data mongodb:
Include the following in the pom.xml
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<spring.data.mongodb.version>1.0.0.RC1</spring.data.mongodb.version>
<spring-data-commons-core>1.2.0.RELEASE</spring-data-commons-core>
</properties>
...
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${spring.data.mongodb.version}</version>
</dependency>
...
Create a new file called application.properties and place it in classpath.
# For Localhost
databaseName=lsDB
dbHost=localhost
Create a Java Annotation based configuration file
@Configuration
@PropertySource(value = "classpath:application.properties")
public class AppConfiguration {
@Autowired
Environment environment;
@Bean
public Mongo mongo() throws UnknownHostException {
String dbHost = environment.getProperty("dbHost");
return new Mongo(dbHost);
}
@Bean
public MongoDbFactory mongoDbFactory() throws Exception {
String databaseName = environment.getProperty("databaseName");
return new SimpleMongoDbFactory(new Mongo(), databaseName);
}
@Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoDbFactory());
}
}
The above code reads the db name and host information from application.properties file and creates the factory and Mongo beans.
Update the spring context file with the following information
<beans xmlns="http://www.springframework.org/schema/beans"
...
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
...
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd>
<!-- Bean Configuration -->
<bean id="appConfiguration" class="com.cv.framework.configuration.AppConfiguration"></bean>
You also might need to tell where your Spring mongo repositories is located (i.e., the package)
<!-- Mongodb Configurations -->
<mongo:repositories base-package="com.cv.ls.mongorepository"
mongo-template-ref="mongoTemplate" />
What is Spring Mongo Repository.
Mongo Repository in spring is actually an interface file that wraps lot of information such as CRUD and query implementation. The developer need to write only the interface and the implementation would be provided by the container.
package com.cv.ls.mongorepository;
@Repository
public interface StudentRepository extends MongoRepository<Student, String>{
public List<Student> findByFirstNameLike(String firstName);
public List<Student> findByUsnLike(String usn);
public List<Student> findByRollNumberLike(String rollNumber);
}
Note:
- @Repository indicates that this is a spring data mongo repository file.
- the interface need to extend from MongoRepository interface where all the method definitions such as save, findAll, findOne(id), delete methods are present.
You can see that we have created some custom methods such as
public List<Student> findByFirstNameLike(String firstName);
Note that these are only method definitions (interface methods).
Thats it !!!, You just need to tell what you want, not how do you do it. The container implementation takes care low level tasks such as getting the connection, executing the query, getting the results, iterating it and converting into list of student objects.
Now u need to use this Repository in the service class.
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
public Student save(Student student) {
Student updatedStudent = studentRepository.save(student);
return updatedStudent;
}
public Student find(String id) {
return studentRepository.findOne(id);
}
public List<Student> findAll() {
return studentRepository.findAll();
}
public void delete(String id) {
studentRepository.delete(id);
}
public List<Student> searchStudentsForCriteria(StudentSearchCriteria studentSearchCriteria) {
if(!studentSearchCriteria.getFirstName().equals("")) {
String firstName = studentSearchCriteria.getFirstName();
List<Student> students = studentRepository.findByFirstNameLike(firstName);
logger.info("Students obtained : " + students);
return students;
}
return null;
}
}
Note:
- In the service class, first autowire the repository object. and invoke the methods accordingly.
- Note that we have not created any method called save or delete, but still you are able to invoke it, yep these comes for free - dont you like Spring data mongodb.
Coool, Now you can create the server implementations in a very fast manner :-)