spring-data-mongodb使用示例

一: 引入所需要的依賴

成都創(chuàng)新互聯(lián)公司基于成都重慶香港及美國等地區(qū)分布式IDC機房數(shù)據(jù)中心構(gòu)建的電信大帶寬,聯(lián)通大帶寬,移動大帶寬,多線BGP大帶寬租用,是為眾多客戶提供專業(yè)資陽主機托管報價,主機托管價格性價比高,為金融證券行業(yè)服務器托管,ai人工智能服務器托管提供bgp線路100M獨享,G口帶寬及機柜租用的專業(yè)成都idc公司。

<!-- 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.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(){

? ? ? ? // 數(shù)據(jù)庫

? ? ? ? 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);

? ? ? ? }

? ? }

}

測試結(jié)果:

[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);

}

當前標題:spring-data-mongodb使用示例
網(wǎng)站URL:http://bm7419.com/article0/ijhdoo.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、定制開發(fā)全網(wǎng)營銷推廣、網(wǎng)站導航軟件開發(fā)、微信公眾號

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

網(wǎng)站托管運營