[本篇文章主要介绍了mongodb对应java的常用增删改查的api,以及和spring集成后mongoTemplate的常用方法使用,废话不多说,直接上代码:1.首先上需要用到的两个实体类User和
但是 在每个页面中都要注入一次xml。
ApplicationContext ctx = new FileSystemXmlApplicationContext(
"WEB-INF/mongoConfig.xml");
MongoTemplate mongoTemplate = (MongoTemplate) ctx
.getBean("mongoTemplate");
而且对class的操作都没进行过方法的封装。
这次 我们用一个搭好的spring+strust+mongodb框架 对mongodb进行操作。
框架下载地址(我的运行环境是myeclipse10)
下载后如果要对项目继续重命名的话: 操作如下图:
框架中的结构如图:
新建需要操作的class类
package com.mongo.entity;
public class User {
private String name;
private String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
操作mongodb的接口和实现类: (基类和继承类)
基类:GenericReposityImpl
package com.mongo.reposity.Impl;
import java.util.List;
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;
import com.mongo.reposity.GenericReposity;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;
public class GenericReposityImpl extends MongoTemplate implements GenericReposity {
public GenericReposityImpl(Mongo mongo, String databaseName) {
super(mongo, databaseName);
}
public List getAllObjects(Class clazz) {
return findAll(clazz);
}
public void saveObject(Object obj) {
insert(obj);
}
public void saveObjects(List objects) {
for (T t : objects) {
insert(t);
}
}
public T getObject(Class clazz, String id) {
return findOne(new Query(Criteria.where("id").is(id)), clazz);
}
public WriteResult updateObject(Class clazz, String id, String name) {
return updateFirst(new Query(Criteria.where("id").is(id)),
Update.update("name", name), clazz);
}
public void deleteObject(Class clazz, String id) {
remove(new Query(Criteria.where("id").is(id)), clazz);
}
public void createDbCollection(Class clazz) {
if (collectionExists(clazz)) {
createCollection(clazz);
}
}
public void dropDbCollection(Class clazz) {
if (collectionExists(clazz)) {
dropCollection(clazz);
}
}
}
接口:GenericReposity
package com.mongo.reposity.Impl;
import java.util.List;
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;
import com.mongo.reposity.GenericReposity;
import com.mongodb.Mongo;
import com.mongodb.WriteResult;
public class GenericReposityImpl extends MongoTemplate implements GenericReposity {
public GenericReposityImpl(Mongo mongo, String databaseName) {
super(mongo, databaseName);
}
public List getAllObjects(Class clazz) {
return findAll(clazz);
}
public void saveObject(Object obj) {
insert(obj);
}
public void saveObjects(List objects) {
for (T t : objects) {
insert(t);
}
}
public T getObject(Class clazz, String id) {
return findOne(new Query(Criteria.where("id").is(id)), clazz);
}
public WriteResult updateObject(Class clazz, String id, String name) {
return updateFirst(new Query(Criteria.where("id").is(id)),
Update.update("name", name), clazz);
}
public void deleteObject(Class clazz, String id) {
remove(new Query(Criteria.where("id").is(id)), clazz);
}
public void createDbCollection(Class clazz) {
if (collectionExists(clazz)) {
createCollection(clazz);
}
}
public void dropDbCollection(Class clazz) {
if (collectionExists(clazz)) {
dropCollection(clazz);
}
}
}
实现类:UserReposityImpl
package com.mongo.reposity.Impl;
import java.util.List;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import com.mongo.entity.User;
import com.mongo.reposity.UserReposity;
import com.mongodb.Mongo;
public class UserReposityImpl extends GenericReposityImpl implements
UserReposity {
public UserReposityImpl(Mongo mongo, String databaseName) {
super(mongo, databaseName);
// TODO Auto-generated constructor stub
}
public List getUsers(int begin, int end) {
return find(new Query().limit(end - begin).skip(begin), User.class);
}
public List getUsers(String Name) {
return find(
new Query(new Criteria("name")
.regex(".*?" + Name + ".*")).limit(5),
User.class);
}
public List getUsers(int begin, int end, List conditions) {
Query query = new Query();
if (conditions != null && conditions.size() > 0) {
for (Condition condition : conditions) {
query.addCriteria(Criteria.where(condition.getKey()).is(
condition.getValue()));
}
}
return find(query.limit(end - begin).skip(begin),User.class);
}
public long getCount(String message) {
Query query = new Query();
query.addCriteria(Criteria.where("message").is(message));
return count(query, User.class);
}
public List getUsersBynames(int begin, int end,
List names) {
Query query = new Query();
query.addCriteria(Criteria.where("name").in(names));
return find(query.limit(end - begin).skip(begin), User.class);
}
public WriteResult updateUserUpdateName(User user,String name) {
String id=user.getId();
return updateFirst(new Query(Criteria.where("id").is(id)),Update.update("name", name),User.class);
}
public void mapReduse(){
DBCollection coll = getCollection("user");
String map = "function() { emit(this.name, {count:1});}";
String reduce = "function(key, values) {var total = 0;for(var i=0;i
String result = "resultCollection";
MapReduceOutput mapReduceOutput = coll.mapReduce(map,
reduce.toString(), result, null);
DBCollection resultColl = mapReduceOutput.getOutputCollection();
DBCursor cursor = resultColl.find();
while (cursor.hasNext()) {
Map object = cursor.next().toMap();
System.out.println(object.get("value"));
// System.out.println(cursor.next().get("value"));
// User user = (User)cursor.next();
}
}
}
实现类接口:UserReposity
package com.mongo.reposity;
import java.util.List;
import com.mongo.entity.User;
public interface UserReposity extends GenericReposity{
public List getUsers(int begin,int end);
/**
*
* @param projectName
* @return
*/
public List getUsers(String projectName);
public List getUsers(int begin, int end, List conditions);
public long getCount(String message);
public List getUsersBynames(int begin, int end,
List names);
public WriteResult updateUserUpdateName(User user,String name);
}
[前面写了一篇 java中操作mongodb但是其中的操作都比较直白 没有经过封装 而且 每次使用前都要先写 数据库名和Ip端口]
条件类(辅助类):
Condition.java
package com.mongo.reposity;
/**
* 条件
*
* @作者 zoe
* @版本
* @更新时间
*/
public class Condition {
private String key;
private Object value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
}
相关配置文件xml:
common-beans.xml 可更改操作的数据库名称 目前为student 和 链接地址 192.168.0.121
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:context="http://www.springframework.org/schema/context"
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.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
info-reposity.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
parent="mongoTemplate">
parent="mongoTemplate">
getDateAcition.java
package com.mongo.action;
import java.util.Map;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.mapreduce.MapReduceOptions;
import org.springframework.data.mongodb.core.mapreduce.MapReduceResults;
import com.mongo.entity.User;
import com.mongo.reposity.UserReposity;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MapReduceOutput;
import com.opensymphony.xwork2.ActionSupport;
public class getDataAction extends ActionSupport {
/**
*
*/
private UserReposity userReposity;
public void setUserReposity(UserReposity userReposity) {
this.userReposity = userReposity;
}
private JSONObject user;
private static final long serialVersionUID = 535742118015700220L;
@Override
public String execute() {
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(false);
// jsonConfig.setExcludes(new String[] { "name" });
jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
// 新增数据
// User u=new User();
// u.setName("zoe");
// u.setMessage("first blood");
// userReposity.saveObject(u);
// System.out.println("写入完成"+u.toString());
// //查询数据
// //获取全部
// List us=userReposity.getAllObjects(User.class);
// //从数目上查询取0到1000
// List us1=userReposity.getUsers(0, 1000);
// //条件查询
// List cds=new ArrayList();
// Condition cd=new Condition();
// cd.setKey("name");
// cd.setValue("zoe");
// cds.add(cd);
// List us2=userReposity.getUsers(0, 1000, cds);
// //模糊查询
// List us3=userReposity.getUsers("oe");
// //查询数量
// long count=userReposity.getCount("first blood");
// //查询属于的集合(in) 不属于(nin)
// List names=new ArrayList();
// names.add("zoe");
// names.add("koe");
// List us4=userReposity.getUsersBynames(0, 1000,names);
//
// //更新
// User u=userReposity.getAllObjects(User.class).get(0);
// userReposity.updateUserUpdateName(u, "joe");
//
// //删除
// userReposity.deleteObject(User.class, "534cea00cf20ab0525bdc53e");
// mapreduce
MongoTemplate m = (MongoTemplate) userReposity;
DBCollection coll = m.getCollection("user"); //集合名
String map = "function() { emit(this.name, {count:1});}";
String reduce = "function(key, values) {var total = 0;for(var i=0;i
String result = "resultCollection";
MapReduceOutput mapReduceOutput = coll.mapReduce(map,
reduce.toString(), result, null);
DBCollection resultColl = mapReduceOutput.getOutputCollection();
DBCursor cursor = resultColl.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
// Map object = cursor.next().toMap();
// System.out.println(object.get("value"));
}
//MongoOperations mongoOps = (MongoOperations) userReposity;
//String map = "function() { emit(this.name, {count:1});}";
//String reduce = "function(key, values) {var total = 0;for(var i=0;i
//try {
//MapReduceResults results = mongoOps.mapReduce("requesterBill",
//map,
//reduce,
new MapReduceOptions().outputCollection("mr_out"),
//User.class);
//for (User valueObject : results) {
//System.out.println(valueObject);
//}
//} catch (Exception e) {
//e.printStackTrace();
//}
// String jsonfacility =
// "{\"id\":\"PublicSecurity\",\"name\":\"数据\",\"value\":\"123\"}";
// user = JSONObject.fromObject(jsonfacility);
//userReposity.mapReduse();
return SUCCESS;
}
public JSONObject getUser() {
return user;
}
public void setUser(JSONObject user) {
this.user = user;
}
}
action相关配置:
action.xml
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
package.xml
/p>
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
插入成功后 可以在数据库中看到:
特殊查询用法积累:
添加在UserReposityImpl中
1.增加排序
public List getByLinkUrlId(int begin, int end, String linkUrlid,String orderField,Sort.Direction direction ) {
Query query = new Query();
query.addCriteria(Criteria.where("pageUrl.linkUrl.id").is(linkUrlid));
return find(query.limit(end - begin).skip(begin).with(new Sort(new Sort.Order(direction, orderField))),User.class);
}
2.按时间段查询
public List getLogs(List conditions,String beginDate,String endDate)
{
Query query = new Query();
if (conditions != null && conditions.size() > 0) {
for (Condition condition : conditions) {
query.addCriteria(Criteria.where(condition.getKey()).regex(
".*?\\" +condition.getValue()+ ".*"));
}
}
query.addCriteria(Criteria.where("crawlTime").lt(new Date(endDate)).gt(new Date(beginDate)));
return find(query,Log.class);
}
3.或者查询
Criteria criteria = new Criteria();
if (!StringUtils.isEmpty(data.get("name"))) {
criteria.orOperator(
Criteria.where("name").regex(
".*" + data.get("name") + ".*", "i"),
Criteria.where("chromosome").regex(
".*" + data.get("name") + ".*", "i"));
}
Query query = Query.query(criteria);
[见蛮多人搜java和Mongodb,那就再写点java操作Mongodb的项目心得。Mongodb的java驱动基本操作可看这里。其实Mongodb的java驱动可以完成大部分的操作和需求。但是当你的doc