(文章的编写虽然不至于花费很多时间,但转载请注明来源。本文参考了:http://liuluo129.iteye.com/blog/1994045,在此基础上进行了部分优化,及详细的介绍了流程)
1.首先引入Maven 依赖,如果不是用Maven管理项目,那么应该下载对应的Jar包并添加到项目lib下
1
2 org.springframework.data
3 spring-data-mongodb
4 1.4.1.RELEASE
5
6
7
8 org.mongodb
9 casbah_2.9.3
10 2.7.0-RC2
11
2.Spring中配置MongoDB,创建 spring-mongo.xml
http://www.springframework.org/schema/context/spring-context-3.2.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-3.2.xsd">
3. config.properties 内容
#--------------MongoDB
mongo.host=localhost
mongo.port=27017mongo.connectionsPerHost=8mongo.threadsAllowedToBlockForConnectionMultiplier=3mongo.connectTimeout=3000mongo.maxWaitTime=1500mongo.autoConnectRetry=truemongo.socketKeepAlive=truemongo.socketTimeout=2000mongo.slaveOk=true
4.将spring-mongo.xml引入到web.xml 目的当然是使Spring容器能检测并加载到容器中
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:/applicationContext-mvc.xml,classpath*:/applicationContext-data-jpa.xml,classpath*:/spring-mongo.xml
1
5.关键的部分 注解及查询套件的构建
QueryField.java
importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;/*** type表示查询类似,默认为equals
* attribute表示要查询的属性,默认为空串,如果为空则为字段名称*/@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)public @interfaceQueryField {
QueryType type()defaultQueryType.EQUALS;
String attribute()default "";
}
QueryType.java
importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.util.StringUtils;importjava.lang.reflect.Field;importjava.util.List;/*** 查询媒介
* 1. equals:相等
* 2. like:mongodb的like查询
* 3. in:用于列表的in类型查询*/
public enumQueryType {
EQUALS {
@OverridepublicCriteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {if(check(queryFieldAnnotation, field, value)) {
String queryField=getQueryFieldName(queryFieldAnnotation, field);returnCriteria.where(queryField).is(value.toString());
}return newCriteria();
}
},
LIKE {
@OverridepublicCriteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {if(check(queryFieldAnnotation, field, value)) {
String queryField=getQueryFieldName(queryFieldAnnotation, field);returnCriteria.where(queryField).regex(value.toString());
}return newCriteria();
}
},
IN {
@OverridepublicCriteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value) {if(check(queryFieldAnnotation, field, value)) {if (value instanceofList) {
String queryField=getQueryFieldName(queryFieldAnnotation, field);//此处必须转型为List,否则会在in外面多一层[]
return Criteria.where(queryField).in((List>)value);
}
}return newCriteria();
}
};private static booleancheck(QueryField queryField, Field field, Object value) {return !(queryField == null || field == null || value == null);
}public abstractCriteria buildCriteria(QueryField queryFieldAnnotation, Field field, Object value);/*** 如果实体bean的字段上QueryField注解没有设置attribute属性时,默认为该字段的名称
*
*@paramfield
*@return
*/
private staticString getQueryFieldName(QueryField queryField, Field field) {
String queryFieldValue=queryField.attribute();if (!StringUtils.hasText(queryFieldValue)) {
queryFieldValue=field.getName();
}returnqueryFieldValue;
}
}
QueryField.java和QueryType.ava的编写的目的是为了公用Dao服务。注意不要引入错误的包。
6.公用Dao的构建
MongoDao.java
packagenet.shopxx.commons.component.mongo;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.core.query.Update;importjava.util.List;public interface MongoDao{//保存一个对象到mongodb
publicT save(T bean);//根据id删除对象
public voiddeleteById(T t);//根据对象的属性删除
public voiddeleteByCondition(T t);//通过条件查询更新数据
public voidupdate(Query query, Update update);//根据id进行更新
public voidupdateById(String id, T t);//通过条件查询实体(集合)
public Listfind(Query query);public ListfindByCondition(T t);//通过一定的条件查询一个实体
publicT findOne(Query query);//通过ID获取记录
publicT get(String id);//通过ID获取记录,并且指定了集合名(表的意思)
publicT get(String id, String collectionName);publicMongoTemplate getMongoTemplate();
}
实现类MongoDaoSupport.java
importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.data.mongodb.core.MongoTemplate;importorg.springframework.data.mongodb.core.query.Criteria;importorg.springframework.data.mongodb.core.query.Query;importorg.springframework.data.mongodb.core.query.Update;importjava.lang.reflect.Field;importjava.lang.reflect.ParameterizedType;importjava.util.List;public abstract class MongoDaoSupport implements MongoDao{
@Autowired
@Qualifier("mongoTemplate")protectedMongoTemplate mongoTemplate;//保存一个对象到mongodb
publicT save(T bean) {
mongoTemplate.save(bean);returnbean;
}//根据id删除对象
public voiddeleteById(T t) {
mongoTemplate.remove(t);
}//根据对象的属性删除
public voiddeleteByCondition(T t) {
Query query=buildBaseQuery(t);
mongoTemplate.remove(query, getEntityClass());
}//通过条件查询更新数据
public voidupdate(Query query, Update update) {
mongoTemplate.updateMulti(query, update,this.getEntityClass());
}//根据id进行更新
public voidupdateById(String id, T t) {
Query query= newQuery();
query.addCriteria(Criteria.where("id").is(id));
Update update=buildBaseUpdate(t);
update(query, update);
}//通过条件查询实体(集合)
public Listfind(Query query) {return mongoTemplate.find(query, this.getEntityClass());
}public ListfindByCondition(T t) {
Query query=buildBaseQuery(t);returnmongoTemplate.find(query, getEntityClass());
}//通过一定的条件查询一个实体
publicT findOne(Query query) {return mongoTemplate.findOne(query, this.getEntityClass());
}//通过ID获取记录
publicT get(String id) {return mongoTemplate.findById(id, this.getEntityClass());
}//通过ID获取记录,并且指定了集合名(表的意思)
publicT get(String id, String collectionName) {return mongoTemplate.findById(id, this.getEntityClass(), collectionName);
}//根据vo构建查询条件Query
privateQuery buildBaseQuery(T t) {
Query query= newQuery();
Field[] fields=t.getClass().getDeclaredFields();for(Field field : fields) {
field.setAccessible(true);try{
Object value=field.get(t);if (value != null) {
QueryField queryField= field.getAnnotation(QueryField.class);if (queryField != null) {
query.addCriteria(queryField.type().buildCriteria(queryField, field, value));
}
}
}catch(IllegalArgumentException e) {
e.printStackTrace();
}catch(IllegalAccessException e) {
e.printStackTrace();
}
}returnquery;
}privateUpdate buildBaseUpdate(T t) {
Update update= newUpdate();
Field[] fields=t.getClass().getDeclaredFields();for(Field field : fields) {
field.setAccessible(true);try{
Object value=field.get(t);if (value != null) {
update.set(field.getName(), value);
}
}catch(Exception e) {
e.printStackTrace();
}
}returnupdate;
}//获取需要操作的实体类class
@SuppressWarnings("unchecked")protected ClassgetEntityClass() {return ((Class) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
}publicMongoTemplate getMongoTemplate() {returnmongoTemplate;
}
}
7.-------------------------------正式开始使用
>>>实体
importnet.xxx.commons.component.mongo.QueryField;public class DeviceToken extendsBaseEntity {
@QueryFieldprivateLong uid;
@QueryFieldprivateString token;
@QueryFieldprivateString device;
@QueryFieldprivateString userAgent;publicDeviceToken(Long uid, String token, String device, String userAgent) {this.uid =uid;this.token =token;this.device =device;this.userAgent =userAgent;
}publicLong getUid() {returnuid;
}public voidsetUid(Long uid) {this.uid =uid;
}publicString getToken() {returntoken;
}public voidsetToken(String token) {this.token =token;
}publicString getDevice() {returndevice;
}public voidsetDevice(String device) {this.device =device;
}publicString getUserAgent() {returnuserAgent;
}public voidsetUserAgent(String userAgent) {this.userAgent =userAgent;
}
}
>>>Service
public interface DeviceTokenService extends MongoDao{
}
>>>ServiceImpl
@Service("deviceTokenServiceImpl")public class DeviceTokenServiceImpl extends MongoDaoSupport implementsDeviceTokenService {
}
>>> 应用
@Resourceprivate DeviceTokenService deviceTokenService; //注入到需要应用的文件//查询示例
List dts= deviceTokenService.find(new BasicQuery(new BasicDBObject("uid",uid),new BasicDBObject("userAgent",userAgent)));
具体其他方法的使用可以扩充MongDao 和MongoDaoSupport.