Spring + MongoDb 基本操作

Pom 引用

        
            org.mongodb
            mongo-java-driver
            3.4.2
        
        
        
            org.springframework.data
            spring-data-mongodb
            1.10.4.RELEASE
        

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



    
    
            
                
    
    
    
    
    
        
        

spring-context.xml




    
        
            
                classpath:mongo.properties
            
        
    

    
        
    

    


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 foods = new ArrayList(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));

    }
}

你可能感兴趣的:(Spring + MongoDb 基本操作)