Spring + MongoDb 基本操作

Pom 引用

        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.4.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-mongodb -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.10.4.RELEASE</version>
        </dependency>

mongo.properties

mongo.dbname=test
mongo.host=localhost
mongo.port=27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.connectTimeout=1500
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive= true
mongo.socketTimeout=1500
mongo.slaveOk=true

spring-mongo.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" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
          http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
          http://www.springframework.org/schema/context 
          http://www.springframework.org/schema/context/spring-context-4.2.xsd 
          http://www.springframework.org/schema/data/mongo 
          http://www.springframework.org/schema/data/mongo/spring-mongo-1.7.xsd 
          http://www.springframework.org/schema/data/repository
          http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd
          http://www.springframework.org/schema/util 
          http://www.springframework.org/schema/util/spring-util-4.2.xsd" 
        default-lazy-init="default">
    
    <!--credentials的配置形式是:用户名:密码@默认数据库-->
    <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" >        
        <mongo:client-options  write-concern="SAFE"
            connections-per-host="${mongo.connectionsPerHost}" 
            threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" 
            connect-timeout="${mongo.connectTimeout}" 
            max-wait-time="${mongo.maxWaitTime}" 
            socket-timeout="${mongo.socketTimeout}"/>        
    </mongo:mongo-client>
    
    <mongo:db-factory id="mongoDbFactory" dbname="${mongo.dbname}" mongo-ref="mongoClient" />
    
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>    
</beans>

spring-context.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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
   http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="configRealm"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="locations">
            <list>
                <value>classpath:mongo.properties</value>
            </list>
        </property>
    </bean>

    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="properties" ref="configRealm" />
    </bean>

    <import resource="spring-mongo.xml" />

</beans>

Food 实体类, mapping MongoDb中的collection

package com.test;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.PersistenceConstructor;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

@Document(collection = "foods")
public class Food {

    @PersistenceConstructor
    public Food(int id, String name, double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    @Id
    private String _objectId;

    @Field("id")
    private int id;
    private String name;
    private double price;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String get_objectId() {
        return _objectId;
    }

    public void set_objectId(String _objectId) {
        this._objectId = _objectId;
    }

    @Override
    public String toString() {
        return String.format("{Id:%s , Name:%s , Price:%s}", id, name, price);
    }

}

测试类

package com.test;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

//http://docs.spring.io/spring-data/mongodb/docs/current/api/org/springframework/data/mongodb/core/query
public class Main {

    static MongoTemplate mongoTemplate = null;

    static {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
        mongoTemplate = (MongoTemplate) context.getBean("mongoTemplate");
    }

    public static void main(String[] args) {
        // test_Update();
        // test_Delete();
        test_Find();

    }

    /**
     * add some test data
     */
    static void initSome() {
        List<Food> foods = new ArrayList<Food>(10);
        String[] names = { "rice", "bread", "milk", "egg", "potato", "tomato", "banana", "orange", "cake", "canddy" };
        double[] prices = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 };
        for (int i = 0; i < 10; i++) {
            Food food = new Food(i + 1, names[i], prices[i]);
            foods.add(food);
        }
        mongoTemplate.insertAll(foods);
    }

    /**
     * clean all the data in foods
     */
    static void cleanFoods() {
        mongoTemplate.findAllAndRemove(new Query(), Food.class);
    }

    static void test_Update() {
        cleanFoods();
        initSome();

        Criteria criteria = new Criteria("id");
        criteria.is(1);
        Query query = new Query(criteria);

        System.out.println("Before update:");
        System.out.println(mongoTemplate.find(query, Food.class));

        Update update = new Update();
        update.set("price", 100);
        mongoTemplate.updateFirst(query, update, Food.class);

        System.out.println("After update:");
        System.out.println(mongoTemplate.find(query, Food.class));

    }

    static void test_Delete() {
        cleanFoods();
        initSome();

        Criteria criteria = new Criteria("id");
        criteria.is(1);
        Query query = new Query(criteria);

        System.out.println("Before delete count:");
        System.out.println(mongoTemplate.count(new Query(), Food.class));

        mongoTemplate.findAllAndRemove(query, Food.class);

        System.out.println("After delete count:");
        System.out.println(mongoTemplate.count(new Query(), Food.class));
    }

    static void test_Find() {
        cleanFoods();
        initSome();

        // where price=5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.is(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price <5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.lt(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price <=5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.lte(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price >5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.gt(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price >=5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.gte(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price !=5
        // Criteria criteriaDefinition = new Criteria("price");
        // criteriaDefinition.ne(5);
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price =9 and id>8
        // Criteria criteriaDefinition_price = new Criteria("price");
        // criteriaDefinition_price.is(9);
        //
        // Criteria criteriaDefinition_Id = new Criteria("id");
        // criteriaDefinition_Id.gt(8);
        //
        // Criteria criteriaDefinition_and = new Criteria();
        // criteriaDefinition_and.andOperator(criteriaDefinition_price,criteriaDefinition_Id);
        //
        // Query query = new Query(criteriaDefinition_and);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where price>5 or name=rice
        // Criteria criteriaDefinition_price = new Criteria("price");
        // criteriaDefinition_price.gt(9);
        //
        // Criteria criteriaDefinition_name = new Criteria("name");
        // criteriaDefinition_name.is("rice");
        //
        // Criteria criteria_or = new Criteria();
        // criteria_or.orOperator(criteriaDefinition_price,criteriaDefinition_name);
        //
        // Query query = new Query(criteria_or);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where (price>5 or name=rice) and id>8
        // Criteria criteriaDefinition_price = new Criteria("price");
        // criteriaDefinition_price.gt(9);
        //
        // Criteria criteriaDefinition_name = new Criteria("name");
        // criteriaDefinition_name.is("rice");
        //
        // Criteria criteria_or = new Criteria();
        // criteria_or.orOperator(criteriaDefinition_price,
        // criteriaDefinition_name);
        //
        // Criteria criteriaDefinition_id = new Criteria("id");
        // criteriaDefinition_id.gt(8);
        //
        // Criteria criteria_and = new Criteria();
        // criteria_and.andOperator(criteria_or, criteriaDefinition_id);
        //
        // Query query = new Query(criteria_and);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // where name in ('bread','cake')
        // Criteria criteriaDefinition = new Criteria("name");
        // criteriaDefinition.in(Arrays.asList("bread", "cake"));
        // Query query = new Query(criteriaDefinition);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // order by id desc
        // Order order = new Order(Sort.Direction.DESC, "id");
        // Sort sort = new Sort(order);
        // Query query = new Query();
        // query.with(sort);
        // System.out.println(mongoTemplate.find(query, Food.class));

        // limit 3
        Pageable pageable = new PageRequest(1, 3);
        Query query = new Query();
        query.with(pageable);
        System.out.println(mongoTemplate.find(query, Food.class));

    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,980评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,178评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,868评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,498评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,492评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,521评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,910评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,569评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,793评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,559评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,639评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,342评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,931评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,904评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,144评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,833评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,350评论 2 342

推荐阅读更多精彩内容