我们前面写了一篇 : java-spring与mongodb的整合方式一 手动注入xml
但是 在每个页面中都要注入一次xml。
ApplicationContext ctx = new FileSystemXmlApplicationContext( "WEB-INF/mongoConfig.xml"); MongoTemplate mongoTemplate = (MongoTemplate) ctx .getBean("mongoTemplate");
而且对class的操作都没进行过方法的封装。
这次 我们用一个搭好的spring+strust+mongodb框架 对mongodb进行操作。
框架下载地址(我的运行环境是myeclipse10)
mongodb+spring+strust框架完整示例版本
下载后如果要对项目继续重命名的话: 操作如下图:
框架中的结构如图:
新建需要操作的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<T> extends MongoTemplate implements GenericReposity<T> { public GenericReposityImpl(Mongo mongo, String databaseName) { super(mongo, databaseName); } public List<T> getAllObjects(Class<T> clazz) { return findAll(clazz); } public void saveObject(Object obj) { insert(obj); } public void saveObjects(List<T> objects) { for (T t : objects) { insert(t); } } public T getObject(Class<T> clazz, String id) { return findOne(new Query(Criteria.where("id").is(id)), clazz); } public WriteResult updateObject(Class<T> clazz, String id, String name) { return updateFirst(new Query(Criteria.where("id").is(id)), Update.update("name", name), clazz); } public void deleteObject(Class<T> clazz, String id) { remove(new Query(Criteria.where("id").is(id)), clazz); } public void createDbCollection(Class<T> clazz) { if (collectionExists(clazz)) { createCollection(clazz); } } public void dropDbCollection(Class<T> clazz) { if (collectionExists(clazz)) { dropCollection(clazz); } } }
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<T> extends MongoTemplate implements GenericReposity<T> { public GenericReposityImpl(Mongo mongo, String databaseName) { super(mongo, databaseName); } public List<T> getAllObjects(Class<T> clazz) { return findAll(clazz); } public void saveObject(Object obj) { insert(obj); } public void saveObjects(List<T> objects) { for (T t : objects) { insert(t); } } public T getObject(Class<T> clazz, String id) { return findOne(new Query(Criteria.where("id").is(id)), clazz); } public WriteResult updateObject(Class<T> clazz, String id, String name) { return updateFirst(new Query(Criteria.where("id").is(id)), Update.update("name", name), clazz); } public void deleteObject(Class<T> clazz, String id) { remove(new Query(Criteria.where("id").is(id)), clazz); } public void createDbCollection(Class<T> clazz) { if (collectionExists(clazz)) { createCollection(clazz); } } public void dropDbCollection(Class<T> 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<User> implements UserReposity { public UserReposityImpl(Mongo mongo, String databaseName) { super(mongo, databaseName); // TODO Auto-generated constructor stub } public List<User> getUsers(int begin, int end) { return find(new Query().limit(end - begin).skip(begin), User.class); } public List<User> getUsers(String Name) { return find( new Query(new Criteria("name") .regex(".*?" + Name + ".*")).limit(5), User.class); } public List<User> getUsers(int begin, int end, List<Condition> 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<User> getUsersBynames(int begin, int end, List<String> 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<values.length;i++){total += values[i].count;}return {count:total};}"; 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<User>{ public List<User> getUsers(int begin,int end); /** * * @param projectName * @return */ public List<User> getUsers(String projectName); public List<User> getUsers(int begin, int end, List<Condition> conditions); public long getCount(String message); public List<User> getUsersBynames(int begin, int end, List<String> names); public WriteResult updateUserUpdateName(User user,String name); }
条件类(辅助类):
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
<?xml version="1.0" encoding="utf-8"?> <!-- 指定Spring配置文件的Schema信息 --> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongo" ref="mongo" /> <constructor-arg name="databaseName" value="student"/> </bean> <bean id="mongo" class="org.springframework.data.mongodb.core.MongoFactoryBean"> <property name="host" value="192.168.0.121"/> <property name="port" value="27017"/> </bean> </beans>
<?xml version="1.0" encoding="GBK"?> <!-- 指定Spring配置文件的Schema信息 --> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <!-- 配置DAO组件的模板 --> <bean id="genericReposity" class="com.mongo.reposity.Impl.GenericReposityImpl" parent="mongoTemplate"> </bean> <bean id="userReposity" class="com.mongo.reposity.Impl.UserReposityImpl" parent="mongoTemplate"> </bean> </beans>
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<User> us=userReposity.getAllObjects(User.class); // //从数目上查询取0到1000 // List<User> us1=userReposity.getUsers(0, 1000); // //条件查询 // List<Condition> cds=new ArrayList<Condition>(); // Condition cd=new Condition(); // cd.setKey("name"); // cd.setValue("zoe"); // cds.add(cd); // List<User> us2=userReposity.getUsers(0, 1000, cds); // //模糊查询 // List<User> us3=userReposity.getUsers("oe"); // //查询数量 // long count=userReposity.getCount("first blood"); // //查询属于的集合(in) 不属于(nin) // List<String> names=new ArrayList<String>(); // names.add("zoe"); // names.add("koe"); // List<User> 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<values.length;i++){total += values[i].count;}return {count:total};}"; 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<values.length;i++){total += values[i].count;}return {count:total};}"; // try { // MapReduceResults<User> 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
<?xml version="1.0" encoding="GBK"?> <!-- 指定Spring配置文件的Schema信息 --> <beans xmlns="http://www.springframework.org/schema/beans" 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"> <!-- 配置DAO组件的模板 --> <bean id="getData" class="com.mongo.action.getDataAction" > <property name="userReposity" ref="userReposity"></property> </bean> </beans>
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="data" extends="zoe-default" namespace="/data"> <!-- 根据项目 --> <action name="getData" class="getData"> <result type="json"></result> </action> </package> </struts>
特殊查询用法积累:
添加在UserReposityImpl中
1.增加排序
public List<User> 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<Log> getLogs(List<Condition> 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); }