spring-data-mongodb使用示例

x33g5p2x  于2021-12-25 转载在 Go  
字(18.9k)|赞(0)|评价(0)|浏览(396)

一: 引入所需要的依赖

<!-- mongodb -->
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>3.3.0</version>
</dependency>

<!-- spring-data-mongodb -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.9.4.RELEASE</version>
</dependency>

二:mongodb与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" 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">

    <!-- MongoDB -->
    <mongo:mongo id="mongo" host="127.0.0.1" port="27017">
    </mongo:mongo>

    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg ref="mongo" />
        <constructor-arg name="databaseName" value="mydb" />
    </bean>
</beans>

三: 测试

实体类: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.SpringJUnit4ClassRunner;

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(SpringJUnit4ClassRunner.class)
public class MongoDBTest extends AbstractJUnit4SpringContextTests{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Before
    public void tearUp(){
        // 数据库
        DB db = mongoTemplate.getDb();
        System.out.println(db.getName());

        // 获取所有集合
        Set<String> 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<Member> 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<Member> 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<Member> 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<Member> 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<Member> 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<Member> 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<Member> 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<Member> 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);

    <T> DBCollection createCollection(Class<T> entityClass);

    <T> DBCollection createCollection(Class<T> entityClass, CollectionOptions collectionOptions);

    DBCollection createCollection(String collectionName);

    DBCollection createCollection(String collectionName, CollectionOptions collectionOptions);

    Set<String> getCollectionNames();

    DBCollection getCollection(String collectionName);

    <T> boolean collectionExists(Class<T> entityClass);

    boolean collectionExists(String collectionName);

    <T> void dropCollection(Class<T> entityClass);

    void dropCollection(String collectionName);

    <T> List<T> findAll(Class<T> entityClass);
    <T> List<T> findAll(Class<T> entityClass, String collectionName);

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

    <O> AggregationResults<O> aggregate(TypedAggregation<?> aggregation, String collectionName, Class<O> outputType);
    <O> AggregationResults<O> aggregate(TypedAggregation<?> aggregation, Class<O> outputType);
    <O> AggregationResults<O> aggregate(Aggregation aggregation, Class<?> inputType, Class<O> outputType);
    <O> AggregationResults<O> aggregate(Aggregation aggregation, String collectionName, Class<O> outputType);

    <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,
            Class<T> entityClass);
    <T> MapReduceResults<T> mapReduce(String inputCollectionName, String mapFunction, String reduceFunction,
            MapReduceOptions mapReduceOptions, Class<T> entityClass);
    <T> MapReduceResults<T> mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,
            Class<T> entityClass);
    <T> MapReduceResults<T> mapReduce(Query query, String inputCollectionName, String mapFunction, String reduceFunction,
            MapReduceOptions mapReduceOptions, Class<T> entityClass);

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

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

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

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

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

    <T> T findAndModify(Query query, Update update, Class<T> entityClass);
    <T> T findAndModify(Query query, Update update, Class<T> entityClass, String collectionName);
    <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass);
    <T> T findAndModify(Query query, Update update, FindAndModifyOptions options, Class<T> entityClass,
            String collectionName);

    <T> T findAndRemove(Query query, Class<T> entityClass);
    <T> T findAndRemove(Query query, Class<T> 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<? extends Object> batchToSave, Class<?> entityClass);
    void insert(Collection<? extends Object> batchToSave, String collectionName);
    void insertAll(Collection<? extends Object> 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);

    <T> List<T> findAllAndRemove(Query query, String collectionName);

    <T> List<T> findAllAndRemove(Query query, Class<T> entityClass);

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

}

相关文章

http://www.what21.com/database/mongodb/mongodb-basis/java-query.html

相关文章