spring mongodb學習

來源:互聯網
上載者:User
  spring mongodb目前是M3,需要配合的是spring 3.0.5及JDK 1.6下,下面舉例子

說明:

1 啟動一個mongodb資料庫

    ./mongodb-xxxxxxx/bin/mongod --dbpath=/mongodb

2 例子中,把20個Person對象入mongodb資料庫,算其平均年齡

  

@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 編寫商務邏輯類,調用mongodb,代碼如下:

 

@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 配置spring設定檔

 

<?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 最後啟動的主類

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.