spring-data-mongodb使用示例

一: 引入所需要的依赖

成都创新互联公司基于成都重庆香港及美国等地区分布式IDC机房数据中心构建的电信大带宽,联通大带宽,移动大带宽,多线BGP大带宽租用,是为众多客户提供专业资阳主机托管报价,主机托管价格性价比高,为金融证券行业服务器托管,ai人工智能服务器托管提供bgp线路100M独享,G口带宽及机柜租用的专业成都idc公司。

    org.mongodb

    mongo-java-driver

    3.3.0

    org.springframework.data

    spring-data-mongodb

    1.9.4.RELEASE

二:mongodb与Spring集成

    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"

    xsi:schemaLocation="http://www.springframework.org/schema/context

          http://www.springframework.org/schema/context/spring-context.xsd

          http://www.springframework.org/schema/data/mongo

          http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd

          http://www.springframework.org/schema/beans

          http://www.springframework.org/schema/beans/spring-beans.xsd">

   

   

   

   

       

       

   

三: 测试

实体类:Member

package com.mengdee.manager.domain;

import java.io.Serializable;

public class Member implements Serializable {

    private static final long serialVersionUID = 5157900066984701447L;

    private Integer id;

    private String username;

    private String password;

    private Integer sex;

    private Integer age;

    private String email;

    public Member(Integer id, String username, String password, Integer sex, Integer age, String email) {

        super();

        this.id = id;

        this.username = username;

        this.password = password;

        this.sex = sex;

        this.age = age;

        this.email = email;

    }

    // getter && setter 

    @Override

    public String toString() {

        return "Member [id=" + id + ", username=" + username + ", password=" + password + ", sex=" + sex + ", age="

                + age + ", email=" + email + "]";

    }

}

MongoDBTest

package com.mengdee.manager.user;

import java.util.List;

import java.util.Set;

import java.util.regex.Pattern;

import org.junit.Before;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Sort;

import org.springframework.data.domain.Sort.Direction;

import org.springframework.data.mongodb.core.MongoTemplate;

import org.springframework.data.mongodb.core.mapreduce.GroupBy;

import org.springframework.data.mongodb.core.mapreduce.GroupByResults;

import org.springframework.data.mongodb.core.query.Criteria;

import org.springframework.data.mongodb.core.query.Query;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;

import org.springframework.test.context.junit4.SpringJUnit4Cla***unner;

import com.mengdee.manager.domain.Member;

import com.mongodb.BasicDBList;

import com.mongodb.BasicDBObject;

import com.mongodb.DB;

@ContextConfiguration(locations = {"classpath:conf/spring/spring-*.xml"})

@RunWith(SpringJUnit4Cla***unner.class)

public class MongoDBTest extends AbstractJUnit4SpringContextTests{

    @Autowired

    private MongoTemplate mongoTemplate;

    @Before

    public void tearUp(){

        // 数据库

        DB db = mongoTemplate.getDb();

        System.out.println(db.getName());

        // 获取所有集合

        Set collectionNames = mongoTemplate.getCollectionNames();

        System.out.println(collectionNames);

        for (String collectionName : collectionNames) {

            long count = mongoTemplate.count(new Query(), Member.class);

            System.out.println("total doc count:" + count);

            if ("member".equals(collectionName)) {

                // 获取指定的集合对应的文档

                List members = mongoTemplate.findAll(Member.class, collectionName);

                printMembers("findAll", members);

            }

        }

        boolean collectionExists = mongoTemplate.collectionExists(Member.class);

        System.out.println("member collection isExists:" + collectionExists);

        if (collectionExists) {

//          mongoTemplate.dropCollection(Member.class);

        }

    }

    // 在保存集合时,如果集合不存在,集合的名字默认为实体类的名字,名字全部小写

    // insert : 当_id 重复插入时会被忽略

    // save: 当_id值相同时就更新, 否则就插入(addOrUpdate)

    @Test

    public void testInsert(){

        Member member1 = new Member(1, "mengdee1", "111111", 1, 15, "mengdee1@163.com");

        mongoTemplate.insert(member1);

        Member member11 = new Member(1, "mengdee11", "222222", 2, 20, "mengdee11@163.com");

        mongoTemplate.insert(member11);

        Member member111 = new Member(1, "mengdee111", "123456", 1, 17, "mengdee111@163.com");

        mongoTemplate.save(member111);

        Member member2 = new Member(2, "mengdee2", "123456", 1, 22, "mengdee2@163.com");

        mongoTemplate.save(member2);

        Member member3 = new Member(3, "vbirdbest1", "123456", 2, 25, "vbirdbest1@126.com");

        mongoTemplate.save(member3);

        Member member4 = new Member(4, "vbirdbest2", "666666", 1, 26, "vbirdbest2@126.com");

        mongoTemplate.save(member4);

        Member member5 = new Member(5, "mengday1", "666666", 2, 28, "mengday1@163.com");

        mongoTemplate.save(member5);

        Member member6 = new Member(6, "mengday2", "888888", 1, 31, "mengday2@163.com");

        mongoTemplate.save(member6);

        Member member7 = new Member(7, "大法师", "888888", 2, 33, "mengdee11@163.com");

        mongoTemplate.save(member7);

        Member member8 = new Member(8, "小法海", "123456", 1, 35, "mengdee11@163.com");

        mongoTemplate.save(member8);

    }

    @Test

    public void testFind() {

        // findById

        Member member = mongoTemplate.findById(5, Member.class);

        System.out.println("findById: id=5: \n" + member);

        // where is

        Query query = new Query();

        query.addCriteria(Criteria.where("id").is(7));

        member = mongoTemplate.findOne(query, Member.class);

        System.out.println("\nfindOne id is 7 \n" + member);

        // 多条键查询 andOperator(相当于SQL中的 and并且)

        Criteria andCriatira = new Criteria();

        andCriatira.andOperator(Criteria.where("age").gte(31), Criteria.where("password").is("888888"));

        List result = mongoTemplate.find(new Query(andCriatira), Member.class);

        printMembers("where age >= 31 and password = 888888", result);

        // or

        Criteria orCriatira = new Criteria();

        orCriatira.orOperator(Criteria.where("id").in(2, 3, 4, 5), Criteria.where("sex").is(1));

        List result2 = mongoTemplate.find(new Query(orCriatira), Member.class);

        printMembers("id in (2, 3, 4) or sex = 1", result2);

        //*************************模糊查询 **************************

        // 左匹配  LIKE 'mengday%'

        Pattern pattern = Pattern.compile("^mengday.*$", Pattern.CASE_INSENSITIVE);

        Query regexQuery = new Query(Criteria.where("username").regex(pattern));

        List findList = mongoTemplate.find(regexQuery, Member.class);

        printMembers("^mengday.*$", findList);

        // 右匹配  LIKE '%@126.com'

        pattern = Pattern.compile("^.*@126.com$", Pattern.CASE_INSENSITIVE);

        regexQuery = new Query(Criteria.where("email").regex(pattern));

        findList = mongoTemplate.find(regexQuery, Member.class);

        printMembers("^.*@126.com$", findList);

        // 模糊匹配  LIKE '%法%'

        pattern = Pattern.compile("^.*法.*$", Pattern.CASE_INSENSITIVE);

        regexQuery = new Query(Criteria.where("username").regex(pattern));

        findList = mongoTemplate.find(regexQuery, Member.class);

        printMembers("^.*法.*$", findList);

        // 完全匹配  = 'mengdee111'

        pattern = Pattern.compile("^mengdee111$", Pattern.CASE_INSENSITIVE);

        regexQuery = new Query(Criteria.where("username").regex(pattern));

        findList = mongoTemplate.find(regexQuery, Member.class);

        printMembers("^mengdee111$", findList);

        // 分页

        int page = 1;

        int pageSize = 5;

        int offset = (page - 1) * pageSize;

        query = new Query();

        Sort sort = new Sort(Direction.DESC, "id");

        query.with(sort).skip(offset).limit(pageSize);

        List members = mongoTemplate.find(query, Member.class);

        printMembers("page limit 0, 5", members);

        // group

        System.out.println("\nwhere age > 18 group by password");

        GroupBy groupBy = GroupBy.key("password")

                .initialDocument("{'sum':0, 'count':0}")

                .reduceFunction("function (doc, prev){ prev.sum += doc.age; prev.count += 1; }");

        GroupByResults groupResult = mongoTemplate.group(Criteria.where("age").gt(18), "member", groupBy, Member.class);

        BasicDBList list = (BasicDBList)groupResult.getRawResults().get("retval");

        for (int i = 0; i < list.size(); i++) {

            BasicDBObject object = (BasicDBObject)list.get(i);

            System.out.println(object);

        }

    }

    @Test

    public void testUpdate() {

        List members = mongoTemplate.find(new Query(Criteria.where("id").in(1, 2, 3, 8)), Member.class);

        printMembers("update befor\n", members);

        Update update = new Update();

        update.set("password", "abcdef");

        update.inc("age", -1);

        mongoTemplate.updateMulti(new Query(Criteria.where("id").in(1, 2, 3, 8)), update, Member.class);

        members = mongoTemplate.find(new Query(Criteria.where("id").in(1, 2, 3, 8)), Member.class);

        printMembers("update after\n", members);

    }

    private void printMembers(String tips, List findList) {

        System.out.println("\n" + tips);

        for (Member member : findList) {

            System.out.println(member);

        }

    }

}

测试结果:

[member]

total doc count:8

findAll

Member [id=1, username=mengdee111, password=123456, sex=1, age=17, email=mengdee111@163.com]

Member [id=2, username=mengdee2, password=123456, sex=1, age=22, email=mengdee2@163.com]

Member [id=3, username=vbirdbest1, password=123456, sex=2, age=25, email=vbirdbest1@126.com]

Member [id=4, username=vbirdbest2, password=666666, sex=1, age=26, email=vbirdbest2@126.com]

Member [id=5, username=mengday1, password=666666, sex=2, age=28, email=mengday1@163.com]

Member [id=6, username=mengday2, password=888888, sex=1, age=31, email=mengday2@163.com]

Member [id=7, username=大法师, password=888888, sex=2, age=33, email=mengdee11@163.com]

Member [id=8, username=小法海, password=123456, sex=1, age=35, email=mengdee11@163.com]

member collection isExists:true

findById: id=5: 

Member [id=5, username=mengday1, password=666666, sex=2, age=28, email=mengday1@163.com]

findOne id is 7 

Member [id=7, username=大法师, password=888888, sex=2, age=33, email=mengdee11@163.com]

where age >= 31 and password = 888888

Member [id=6, username=mengday2, password=888888, sex=1, age=31, email=mengday2@163.com]

Member [id=7, username=大法师, password=888888, sex=2, age=33, email=mengdee11@163.com]

id in (2, 3, 4) or sex = 1

Member [id=1, username=mengdee111, password=123456, sex=1, age=17, email=mengdee111@163.com]

Member [id=2, username=mengdee2, password=123456, sex=1, age=22, email=mengdee2@163.com]

Member [id=3, username=vbirdbest1, password=123456, sex=2, age=25, email=vbirdbest1@126.com]

Member [id=4, username=vbirdbest2, password=666666, sex=1, age=26, email=vbirdbest2@126.com]

Member [id=5, username=mengday1, password=666666, sex=2, age=28, email=mengday1@163.com]

Member [id=6, username=mengday2, password=888888, sex=1, age=31, email=mengday2@163.com]

Member [id=8, username=小法海, password=123456, sex=1, age=35, email=mengdee11@163.com]

^mengday.*$

Member [id=5, username=mengday1, password=666666, sex=2, age=28, email=mengday1@163.com]

Member [id=6, username=mengday2, password=888888, sex=1, age=31, email=mengday2@163.com]

^.*@126.com$

Member [id=3, username=vbirdbest1, password=123456, sex=2, age=25, email=vbirdbest1@126.com]

Member [id=4, username=vbirdbest2, password=666666, sex=1, age=26, email=vbirdbest2@126.com]

^.*法.*$

Member [id=7, username=大法师, password=888888, sex=2, age=33, email=mengdee11@163.com]

Member [id=8, username=小法海, password=123456, sex=1, age=35, email=mengdee11@163.com]

^mengdee111$

Member [id=1, username=mengdee111, password=123456, sex=1, age=17, email=mengdee111@163.com]

page limit 0, 5

Member [id=8, username=小法海, password=123456, sex=1, age=35, email=mengdee11@163.com]

Member [id=7, username=大法师, password=888888, sex=2, age=33, email=mengdee11@163.com]

Member [id=6, username=mengday2, password=888888, sex=1, age=31, email=mengday2@163.com]

Member [id=5, username=mengday1, password=666666, sex=2, age=28, email=mengday1@163.com]

Member [id=4, username=vbirdbest2, password=666666, sex=1, age=26, email=vbirdbest2@126.com]

where age > 18 group by password

{ "password" : "123456" , "sum" : 82.0 , "count" : 3.0}

{ "password" : "666666" , "sum" : 54.0 , "count" : 2.0}

{ "password" : "888888" , "sum" : 64.0 , "count" : 2.0}

四:常用的类和常用的方法

Query

public class Query {

    public static Query query(CriteriaDefinition criteriaDefinition);

    public Query(CriteriaDefinition criteriaDefinition);

    public Query addCriteria(CriteriaDefinition criteriaDefinition);

    public Query skip(int skip);

    public Query limit(int limit);

    public Query withHint(String name);

    public Query with(Pageable pageable);

    public Query with(Sort sort);

}

Criteria

public class Criteria implements CriteriaDefinition {

    public Criteria(String key);

    public static Criteria where(String key);

    public Criteria and(String key);

    public Criteria is(Object o);

    public Criteria ne(Object o);

    public Criteria lt(Object o);

    public Criteria lte(Object o);

    public Criteria gt(Object o);

    public Criteria gte(Object o);

    public Criteria in(Object... o);

    public Criteria nin(Object... o);

    public Criteria not();

    public Criteria regex(String re);

    public Criteria andOperator(Criteria... criteria);

    public Criteria orOperator(Criteria... criteria);

    public Criteria mod(Number value, Number remainder);

    public Criteria all(Object... o);

    public Criteria size(int s);

    public Criteria exists(boolean b);

    public Criteria type(int t);

}

Update

public class Update {

    public static Update update(String key, Object value);

    public Update set(String key, Object value);

    public Update inc(String key, Number inc);

    public Update push(String key, Object value);

    public Update pop(String key, Position pos);

}

MongoTemplate

public class MongoTemplate implements MongoOperations {

    String getCollectionName(Class entityClass);

    DBCollection createCollection(Class entityClass);

    DBCollection createCollection(Class entityClass, CollectionOptions collectionOptions);

    DBCollection createCollection(String collectionName);

    DBCollection createCollection(String collectionName, CollectionOptions collectionOptions);

    Set getCollectionNames();

    DBCollection getCollection(String collectionName);

    boolean collectionExists(Class entityClass);

    boolean collectionExists(String collectionName);

    void dropCollection(Class entityClass);

    void dropCollection(String collectionName);

    List findAll(Class entityClass);

    List findAll(Class entityClass, String collectionName);

    GroupByResults group(String inputCollectionName, GroupBy groupBy, Class entityClass);

    GroupByResults group(Criteria criteria, String inputCollectionName, GroupBy groupBy, Class entityClass);

    AggregationResults aggregate(TypedAggregation aggregation, String collectionName, Class outputType);

    AggregationResults aggregate(TypedAggregation aggregation, Class outputType);

    AggregationResults aggregate(Aggregation aggregation, Class inputType, Class outputType);

    AggregationResults aggregate(Aggregation aggregation, String collectionName, Class outputType);

    MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,

            Class entityClass);

    MapReduceResults mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,

            MapReduceOptions mapReduceOptions, Class entityClass);

    MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,

            Class entityClass);

    MapReduceResults mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,

            MapReduceOptions mapReduceOptions, Class entityClass);

    GeoResults geoNear(NearQuery near, Class entityClass);

    GeoResults geoNear(NearQuery near, Class entityClass, String collectionName);

    T findOne(Query query, Class entityClass);

    T findOne(Query query, Class entityClass, String collectionName);

    boolean exists(Query query, String collectionName);

    boolean exists(Query query, Class entityClass);

    boolean exists(Query query, Class entityClass, String collectionName);

    List find(Query query, Class entityClass);

    List find(Query query, Class entityClass, String collectionName);

    T findById(Object id, Class entityClass);

    T findById(Object id, Class entityClass, String collectionName);

    T findAndModify(Query query, Update update, Class entityClass);

    T findAndModify(Query query, Update update, Class entityClass, String collectionName);

    T findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass);

    T findAndModify(Query query, Update update, FindAndModifyOptions options, Class entityClass,

            String collectionName);

    T findAndRemove(Query query, Class entityClass);

    T findAndRemove(Query query, Class entityClass, String collectionName);

    long count(Query query, Class entityClass);

    long count(Query query, String collectionName);

    long count(Query query, Class entityClass, String collectionName);

    void insert(Object objectToSave);

    void insert(Object objectToSave, String collectionName);

    void insert(Collection batchToSave, Class entityClass);

    void insert(Collection batchToSave, String collectionName);

    void insertAll(Collection objectsToSave);

    void save(Object objectToSave);

    void save(Object objectToSave, String collectionName);

    WriteResult upsert(Query query, Update update, Class entityClass);

    WriteResult upsert(Query query, Update update, String collectionName);

    WriteResult upsert(Query query, Update update, Class entityClass, String collectionName);

    WriteResult updateFirst(Query query, Update update, Class entityClass);

    WriteResult updateFirst(Query query, Update update, String collectionName);

    WriteResult updateFirst(Query query, Update update, Class entityClass, String collectionName);

    WriteResult updateMulti(Query query, Update update, Class entityClass);

    WriteResult updateMulti(Query query, Update update, String collectionName);

    WriteResult updateMulti(final Query query, final Update update, Class entityClass, String collectionName);

    WriteResult remove(Object object);

    WriteResult remove(Object object, String collection);

    WriteResult remove(Query query, Class entityClass);

    WriteResult remove(Query query, Class entityClass, String collectionName);

    WriteResult remove(Query query, String collectionName);

    List findAllAndRemove(Query query, String collectionName);

    List findAllAndRemove(Query query, Class entityClass);

    List findAllAndRemove(Query query, Class entityClass, String collectionName);

}


网站标题:spring-data-mongodb使用示例
转载注明:http://azwzsj.com/article/ijhdoo.html