1. maven pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yonyou</groupId>
<artifactId>qa</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>mongo</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>2.0.0.M1</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.21</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
2. spring 配置 spring data mongo 2.x 相比较1.x变化非常大,详情移步:http://docs.spring.io/spring-data/data-mongo/docs/2.0.0.M1/reference/html/
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"
default-lazy-init="false">
<!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongo.properties" />
<!-- 连接配置 -->
<mongo:mongo-client id="mongo" host="101.200.194.213" port="27777" credentials="testuser:111111@testdb">
<mongo:client-options connections-per-host="8"
threads-allowed-to-block-for-connection-multiplier="4"
connect-timeout="1000" max-wait-time="1500"
socket-keep-alive="true" socket-timeout="1500"/>
</mongo:mongo-client>
<!-- 副本集 -->
<!-- <mongo:mongo-client id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/> -->
<mongo:db-factory id="mongoDbFactory" dbname="testdb" mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
<bean id="mongoDao" class="com.yonyou.qa.mongo.MongoDao">
<property name="mongoTemplate" ref="mongoTemplate" />
</bean>
</beans>
3. 自写的api
package com.yonyou.qa.mongo;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.springframework.data.mongodb.core.MongoTemplate;
/**
* mongoDao
* @author jiangleid
*
* 尽量让业务开发人员不用去了解mongoDB
* 提供了相应的CRUD、分页、正则、范围(大于、小于等)
* 后续还会继续扩展、、、、
* 若不能满足时可以直接调用template,更甚至调用mongo的api
*
*/
public interface IMongoDao {
/**
* 插入单个数据
* @param objectToSave
* @param tableName
*/
public void insert(Object objectToSave, String tableName);
/**
* 插入批量数据
* @param batchToSave
* @param tableName
*/
public void insertBath(Collection<? extends Object> batchToSave, String tableName);
/**
* 根据条件删除数据
* @param criteriaMap
* @param tableName
*/
public void deleteByMap(CriteriaMap criteriaMap, String tableName);
/**
* 删除所有数据
* @param tableName
*/
public void deleteAll(String tableName);
/**
* 更新数据
* @param criteriaMap
* @param setMap
* @param tableName
*/
public void update(CriteriaMap criteriaMap, Map<String, Object> setMap, String tableName) ;
/**
* 查询数据
* @param criteriaMap
* @param c
* @param tableName
* @return
*/
public <T> List<T> findByMap(CriteriaMap criteriaMap, Class<T> c, String tableName) ;
/**
* 查询数据,带指定起止行
* @param criteriaMap
* @param c
* @param start
* @param limit
* @param tableName
* @return
*/
public <T> List<T> findByMap(CriteriaMap criteriaMap, Class<T> c, int start,
int limit, String tableName) ;
/**
* 查询数据,带分页
* @param criteriaMap
* @param c
* @param pageNo
* @param pageSize
* @param tableName
* @return
*/
public <T> List<T> findByMap4Page(CriteriaMap criteriaMap, Class<T> c, int pageNo, int pageSize, String tableName) ;
/**
* 查询所有数据
* @param c
* @param tableName
* @return
*/
public <T> List<T> findAll(Class<T> c, String tableName);
/**
* 查询数据并修改,返回修改前的数据
* @param criteriaMap
* @param setMap
* @param c
* @param tableName
* @return
*/
public <T> T findAndModify(CriteriaMap criteriaMap, Map<String, Object> setMap, Class<T> c,
String tableName) ;
/**
* 查询数据并删除,返回删除前的数据
* @param criteriaMap
* @param c
* @param tableName
* @return
*/
public <T> T findAndRemove(CriteriaMap criteriaMap, Class<T> c, String tableName);
/**
* 统计
* @param criteriaMap
* @param tableName
* @return
*/
public long count(CriteriaMap criteriaMap, String tableName);
/**
* spring data mongo 原生接口
* @return
*/
public MongoTemplate getMongoTemplate();
}
package com.yonyou.qa.mongo;
import java.util.Collection;
import java.util.List;
import java.util.Map;
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;
public class MongoDao implements IMongoDao {
private MongoTemplate mongoTemplate;
public MongoTemplate getMongoTemplate() {
return mongoTemplate;
}
public void setMongoTemplate(MongoTemplate mongoTemplate) {
this.mongoTemplate = mongoTemplate;
}
public void insert(Object objectToSave, String tableName) {
mongoTemplate.insert(objectToSave, tableName);
}
public void insertBath(Collection<? extends Object> batchToSave, String tableName) {
mongoTemplate.insert(batchToSave, tableName);
}
public void deleteByMap(CriteriaMap criteriaMap, String tableName) {
Query query = getQuery(criteriaMap);
mongoTemplate.remove(query, tableName);
}
public void deleteAll(String tableName) {
mongoTemplate.dropCollection(tableName);
}
public void update(CriteriaMap criteriaMap, Map<String, Object> setMap, String tableName) {
Query query = getQuery(criteriaMap);
Update update = null;
for (String key : setMap.keySet()) {
Object obj = setMap.get(key);// 得到每个key对用value的值
if (update == null) {
update = Update.update(key, obj);
} else {
update = update.set(key, obj);
}
}
mongoTemplate.updateMulti(query, update, tableName);
}
public <T> List<T> findByMap(CriteriaMap criteriaMap, Class<T> c, String tableName) {
Query query = getQuery(criteriaMap);
return mongoTemplate.find(query, c, tableName);
}
public <T> List<T> findByMap(CriteriaMap criteriaMap, Class<T> c, int skip, int limit, String tableName) {
Query query = getQuery(criteriaMap);
query.skip(skip);
query.limit(limit);
return mongoTemplate.find(query, c, tableName);
}
public <T> List<T> findByMap4Page(CriteriaMap criteriaMap, Class<T> c, int pageNo, int pageSize, String tableName) {
Query query = getQuery(criteriaMap);
query.skip((pageNo - 1) * pageSize).limit(pageSize);
// query = query.skip((pageNo - 1) * pageSize).limit(pageSize);
return mongoTemplate.find(query, c, tableName);
}
public <T> List<T> findAll(Class<T> c, String tableName) {
return mongoTemplate.findAll(c, tableName);
}
public <T> T findAndModify(CriteriaMap criteriaMap, Map<String, Object> setMap, Class<T> c, String tableName) {
Query query = getQuery(criteriaMap);
Update update = getUpdater(setMap);
return mongoTemplate.findAndModify(query, update, c, tableName);
}
public <T> T findAndRemove(CriteriaMap criteriaMap, Class<T> c, String tableName) {
Query query = getQuery(criteriaMap);
return mongoTemplate.findAndRemove(query, c, tableName);
}
public long count(CriteriaMap criteriaMap, String tableName) {
Query query = getQuery(criteriaMap);
return mongoTemplate.count(query, tableName);
}
private Query getQuery(CriteriaMap criteriaMap) {
Criteria criteria = null;
for (String key : criteriaMap.keySet()) {
CriteriaMap.Data d = criteriaMap.get(key);
switch (d.getType()) {
case is:
if (criteria == null) {
criteria = Criteria.where(key).is(d.getObj());
} else {
criteria = criteria.and(key).is(d.getObj());
}
break;
case regex:
if (criteria == null) {
criteria = Criteria.where(key).regex(d.getObj().toString());
} else {
criteria = criteria.and(key).regex(d.getObj().toString());
}
break;
case gt:
if (criteria == null) {
criteria = Criteria.where(key).gt(d.getObj());
} else {
criteria = criteria.and(key).gt(d.getObj());
}
break;
case gte:
if (criteria == null) {
criteria = Criteria.where(key).gte(d.getObj());
} else {
criteria = criteria.and(key).gte(d.getObj());
}
break;
case lt:
if (criteria == null) {
criteria = Criteria.where(key).lt(d.getObj());
} else {
criteria = criteria.and(key).lt(d.getObj());
}
break;
case lte:
if (criteria == null) {
criteria = Criteria.where(key).lte(d.getObj());
} else {
criteria = criteria.and(key).lte(d.getObj());
}
break;
}
}
Query query = new Query(criteria);
// query.addCriteria(criteria);
return query;
}
private Update getUpdater(Map<String, Object> setMap) {
Update updater = null;
for (String key : setMap.keySet()) {
Object obj = setMap.get(key);// 得到每个key对用value的值
if (updater == null) {
updater = Update.update(key, obj);
} else {
updater = updater.set(key, obj);
}
}
return updater;
}
}
package com.yonyou.qa.mongo;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* 条件数据
* @author jiangleid
*
*/
public class CriteriaMap {
private Map<String, Data> map = new HashMap<String, Data>();
public void put(String key, Object value) {
map.put(key, new Data(value));
};
public Data get(String key) {
return map.get(key);
};
public void put(String key, Object value, Type type) {
map.put(key, new Data(value, type));
};
public Set<String> keySet() {
return map.keySet();
}
class Data {
private Type type;
private Object obj;
Data(Object obj) {
this.obj = obj;
this.type = Type.is;
}
Data(Object obj, Type type) {
this.obj = obj;
this.type = type;
}
public Object getObj() {
return obj;
}
public Type getType() {
return type;
}
}
enum Type{
is,regex,gt,gte,lt,lte
}
}
package com.yonyou.qa.mongo;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.bson.Document;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
public class MongoTest {
static ClassPathXmlApplicationContext context = null;
static {
context = new ClassPathXmlApplicationContext(
new String[] { "classpath:spring-mongo.xml" });
context.start();
}
public static void main(String[] args) {
IMongoDao mongoDao = (IMongoDao) context.getBean("mongoDao");
Map m = new HashMap();
// m.put("name", "stone");
// System.out.println(mongoDao.findAll(HashMap.class,"user"));
m.put("name", "tech");
// m.put("age", 111);
// m.put("email", "andy1@zybros.com");
User u = new User();
u.setId(888888);
u.setName("tech");
u.setEmail("tech@vip.com");
u.setPhone("158888888888");
u.setAddrs(Arrays.asList("A", "B", "C"));
Map setM = new HashMap();
setM.put("email", "andy222@zybros.com");
// mongoDao.insert(u, "user");
// mongoDao.getMongoTemplate().insert(m,"user");
CriteriaMap cm = new CriteriaMap();
cm.put("age", 49,CriteriaMap.Type.gte);
System.out.println(mongoDao.findByMap(cm,HashMap.class,"user"));
// System.out.println(mongoDao.findAndModify(cm,setM,HashMap.class,"user"));
// System.out.println(mongoDao.findAll(HashMap.class,"user"));
/****************** 下面是 mongo dirver java *******************/
// String myUserName = "testuser";
// String myPassword = "111111";
//
// //创建个 credential对象
// MongoCredential credential = MongoCredential.createCredential(myUserName, "testdb", myPassword.toCharArray());
// MongoClient mongoClient = new MongoClient(new ServerAddress("101.200.194.213", 27777), Arrays.asList(credential));
// MongoDatabase db = mongoClient.getDatabase("testdb");
// //获得某集合对象
// MongoCollection<Document> mc = db.getCollection("user");
//
// ArrayList<Object> list = mc.find().into(new ArrayList<Object>());
// for (Object object : list) {
// System.out.println(object);
// }
}
}
源码下载:
http://download.csdn.net/detail/stonexmx/9768332