Currently, spring MongoDB is m3 and needs to be used in combination with spring 3.0.5 and JDK 1.6. The following is an example:
Note:
1. Start a MongoDB Database
./MongoDB-xxxxxxx/bin/mongod -- dbpath =/MongoDB
2. In the example, 20 person objects are imported into the MongoDB database to calculate their average age.
@Documentpublic class Person { @Id private String personId; private String name; private String homeTown; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getPersonId() { return personId; } public void setPersonId(final String personId) { this.personId = personId; } public String getName() { return name; } public void setName(final String name) { this.name = name; } public int getAge() { return age; } public void setAge(final int age) { this.age = age; } public String getHomeTown() { return homeTown; } public void setHomeTown(final String homeTown) { this.homeTown = homeTown; } @Override public String toString() { return "Person [id=" + personId + ", name=" + name + ", age=" + age + ", home town=" + homeTown + "]"; }
3. Compile the business logic class and call MongoDB. The Code is as follows:
@Repositorypublic class PersonRepository { static final Logger logger = LoggerFactory.getLogger(PersonRepository.class); @Autowired MongoTemplate mongoTemplate; public void logAllPersons() { List<Person> results = mongoTemplate.findAll(Person.class); logger.info("Total amount of persons: {}", results.size()); logger.info("Results: {}", results); } /** * Calculates the average age of a {@link Person}. * * @return the average age */ public int getAvarageAgeOfPerson() { List<Person> results = mongoTemplate.findAll(Person.class); int age = 0; Iterator<Person> personIterator = results.iterator(); while (personIterator.hasNext()) { Person nextPerson = personIterator.next(); age += nextPerson.getAge(); } return age / results.size(); } public void insertPersonWithNameJohnAndRandomAge() { //get random age between 1 and 100 double age = Math.ceil(Math.random() * 100); Person p = new Person("John", (int) age); mongoTemplate.insert(p); } /** * Create a {@link Person} collection if the collection does not already exists */ public void createPersonCollection() { if (!mongoTemplate.collectionExists(Person.class)) { mongoTemplate.createCollection(Person.class); } } /** * Drops the {@link Person} collection if the collection does already exists */ public void dropPersonCollection() { if (mongoTemplate.collectionExists(Person.class)) { mongoTemplate.dropCollection(Person.class); } }
4. Configure the spring configuration file
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Activate annotation configured components --> <context:annotation-config/> <!-- Scan components for annotations within the configured package --> <context:component-scan base-package="com.jeroenreijn.mongodb.example"> <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration"/> </context:component-scan> <!-- Define the MongoTemplate which handles connectivity with MongoDB --> <bean id="mongoTemplate" class="org.springframework.data.document.mongodb.MongoTemplate"> <constructor-arg name="mongo" ref="mongo"/> <constructor-arg name="databaseName" value="mongodb"/> </bean> <!-- Factory bean that creates the Mongo instance --> <bean id="mongo" class="org.springframework.data.document.mongodb.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>
5. The last started main class
public class MongoDBApp { static final Logger logger = LoggerFactory.getLogger(MongoDBApp.class); public static void main( String[] args ) {logger.info("Bootstrapping MongoDemo application");ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("META-INF/spring/applicationContext.xml"); PersonRepository personRepository = context.getBean(PersonRepository.class); // cleanup person collection before insertion personRepository.dropPersonCollection(); //create person collection personRepository.createPersonCollection(); for(int i=0; i<20; i++) { personRepository.insertPersonWithNameJohnAndRandomAge(); } personRepository.logAllPersons(); logger.info("Avarage age of a person is: {}", personRepository.getAvarageAgeOfPerson()); logger.info("Finished MongoDemo application");}