一、mongodb是什么
MongoDB 是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。
(以上是百度百科的介绍,更多详情请参考mongodb官网 https://www.mongodb.com/ )
二、java中使用spring整合mongodb
我们采用的是spring-data-mongodb 组件整合mongodb ,整合过程十分简单。
mongodb.properties
#mongoDB连接配置 mongo.dbname=myDB mongo.host=192.168.1.129 mongo.port=27017 #mongo.username=root #mongo.password=root #一个线程变为可用的最大阻塞数 #mongo.writeConcern=SAFE mongo.connectionsPerHost=8 #线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #连接超时时间(毫秒) mongo.connectTimeout=1500 #最大等待时间 mongo.maxWaitTime=1500 #自动重连 mongo.autoConnectRetry=true #scoket保持活动 mongo.socketKeepAlive= true #scoket超时时间 mongo.socketTimeout=1500
spring-mongodb.xml (注意spring的版本必须是4以上)
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:cache="http://www.springframework.org/schema/cache" 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-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.3.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.10.xsd"> <mongo:db-factory id="mongoDbFactory" dbname="${mongo.dbname}" mongo-ref="mongoClient"/> <!--credentials的配置形式是:用户名:密码@默认数据库--> <!-- <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.username}:${mongo.password}@${mongo.dbname}" > --> <mongo:mongo-client id="mongoClient" host="${mongo.host}" port="${mongo.port}" > <mongo:client-options connections-per-host="${mongo.connectionsPerHost}" threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" connect-timeout="${mongo.connectTimeout}" max-wait-time="${mongo.maxWaitTime}" socket-timeout="${mongo.socketTimeout}" /> </mongo:mongo-client> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean> </beans>
pom.xml
<!-- slf4j jar包 (api)--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <!-- slf4j jar包 (实现)--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.7</version> </dependency> <!-- spring-data-mongodb 组件 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.10.7.RELEASE</version> </dependency>
ok,以上就整合完成了。
在我们的业务代码中如果需要调用mongodb ,只需要@resources 注入mongoTemplate 这个bean即可。
三、mongodb操作的简单封装(CRUD)
MongoBaseDao.java
package com.tingcream.hplusAdmin.business.other.base; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.List; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.bson.types.ObjectId; 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 org.springframework.stereotype.Component; import com.mongodb.WriteResult; /** * 对mongodb CRUD的简单封装 * @author jelly */ @Component public class MongoBaseDao { @Resource private MongoTemplate mongoTemplate; /** * 根据id查询 * @param _id 主键id * @param entityClass 实体类 * @return T * @author jelly * */ public <T> T findById( String _id,Class<T> entityClass) { return mongoTemplate.findById(_id, entityClass); } /** * 根据id查询 * @param _id 主键id * @param entityClass 实体类 * @param collectionName 集合名称 * @return T * @author jelly * */ public <T> T findById( String _id,Class<T> entityClass,String collectionName) { return mongoTemplate.findById(_id, entityClass,collectionName); } /** * 保存一个实体对象 * @param t * @return T * @author jelly * */ public <T> T save(T t){ mongoTemplate.save(t); return t;//自动主键返回 } /** * * @param t * @param collectionName * @return * @return T * @author jelly * */ public <T> T save(T t,String collectionName){ mongoTemplate.save(t,collectionName); return t;//自动主键返回 } /** * 查询所有实体对象 * @param entityClass * @return List<T> * @author jelly * */ public <T> List<T> findAll(Class<T> entityClass){ return mongoTemplate.findAll(entityClass); } /** * 查询所有实体对象 * @param entityClass * @param collectionName * @return List<T> * @author jelly * */ public <T> List<T> findAll(Class<T> entityClass,String collectionName){ return mongoTemplate.findAll(entityClass,collectionName); } /** * 根据id删除 * @param _id * @param entityClass * @return WriteResult * @author jelly * */ public <T> WriteResult deleteById(String _id,Class<T> entityClass){ Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id))); return mongoTemplate.remove(query, entityClass); } /** * 根据id删除 * @param _id * @param entityClass * @param collectionName * @return WriteResult * @author jelly * */ public <T> WriteResult deleteById(String _id,Class<T> entityClass,String collectionName){ Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id))); return mongoTemplate.remove(query, entityClass,collectionName); } /** * 更新一个实体对象 ,根据_id主键update * @param t * @throws Exception * @return WriteResult * @author jelly * */ public <T> WriteResult updateOne(T t) throws Exception{ //where条件, 根据id 更新 //Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id))); Update update=new Update(); Class<? extends Object> clazz=t.getClass(); //clazz 对象 Field field = clazz.getDeclaredField("_id"); PropertyDescriptor idDescriptor = new PropertyDescriptor(field.getName(), clazz); String _id = (String) idDescriptor.getReadMethod().invoke(t); Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));//查询条件 id BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors= beanInfo.getPropertyDescriptors();//属性描述器数组 for(int i=0;i<propertyDescriptors.length;i++){ //属性描述器 PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); //获得属性名 if(propertyName.equals("class") || propertyName.equals("_id") || propertyName.equals("serialVersionUID")){ continue; } PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz); Method writeMethod= pd.getWriteMethod(); if(writeMethod==null){ continue; } Method readMethod=pd.getReadMethod(); String retType= readMethod.getReturnType().getName(); if(retType.equals(String.class.getName())){//"java.lang.String" String value = (String) readMethod.invoke(t); if(StringUtils.isNotEmpty(value)){ update.set(propertyName, value); } }else { if(readMethod.invoke(t)!=null){ update.set(propertyName, readMethod.invoke(t)); } } } return mongoTemplate.updateFirst(query, update, clazz); } /** * 更新一个实体对象 ,根据_id主键update * @param t * @param collectionName * @throws Exception * @return WriteResult * @author jelly * */ public <T> WriteResult updateOne(T t,String collectionName) throws Exception{ //where条件, 根据id 更新 //Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id))); Update update=new Update(); Class<? extends Object> clazz=t.getClass(); //clazz 对象 Field field = clazz.getDeclaredField("_id"); PropertyDescriptor idDescriptor = new PropertyDescriptor(field.getName(), clazz); String _id = (String) idDescriptor.getReadMethod().invoke(t); Query query =Query.query(Criteria.where("_id").is(new ObjectId(_id)));//查询条件 id BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] propertyDescriptors= beanInfo.getPropertyDescriptors();//属性描述器数组 for(int i=0;i<propertyDescriptors.length;i++){ //属性描述器 PropertyDescriptor descriptor = propertyDescriptors[i]; String propertyName = descriptor.getName(); //获得属性名 if(propertyName.equals("class") || propertyName.equals("_id") || propertyName.equals("serialVersionUID")){ continue; } PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz); Method writeMethod= pd.getWriteMethod(); if(writeMethod==null){ continue; } Method readMethod=pd.getReadMethod(); String retType= readMethod.getReturnType().getName(); if(retType.equals(String.class.getName())){//"java.lang.String" String value = (String) readMethod.invoke(t); if(StringUtils.isNotEmpty(value)){ update.set(propertyName, value); } }else { if(readMethod.invoke(t)!=null){ update.set(propertyName, readMethod.invoke(t)); } } } return mongoTemplate.updateFirst(query, update, clazz,collectionName); } }
ok ~~~