1.引入包
<!-- spring data mongoDB依赖 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.13.3</version>
</dependency>
2.mongodb.properties
mongo.url=mongodb01.banksteel.local:27030,mongodb01.banksteel.local:27031,mongodb01.banksteel.local:27032
mongo.host=192.168.201.110
mongo.password=h#>f^yK5_49q
mongo.port=27030
mongo.username=openerp_log
mongo.database=openerp_log
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
mongo.connectTimeout=1000
mongo.maxWaitTime=1500
mongo.autoConnectRetry=true
mongo.socketKeepAlive=true
mongo.socketTimeout=5000
mongo.slaveOk=true
mongo.writeNumber=1
mongo.writeTimeout=0
mongo.writeFsync=true
3. applicationContext-mongo.xml
<?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: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.0.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/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 标注扫描的类 -->
<!-- 开启注解 -->
<context:component-scan base-package="com.banksteel.openerp.log.provider.dao.impl,com.banksteel.openerp.log.provider.service.impl" />
<!-- 配置数据库的地址和端口 -->
<mongo:mongo id="mongo" replica-set="${mongo.url}">
</mongo:mongo>
<!-- 如果没有创建数据库,就会默认创建数据库 username="root" password="root" -->
<mongo:db-factory id="mongoDbFactory" dbname="${mongo.database}" mongo-ref="mongo"
username="${mongo.username}" password="${mongo.password}"/>
<!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 设定我们的 mongoDbFactory 对象 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
4.MongoBaseDao.java
package com.banksteel.openerp.commons.mongoDBBase.dao;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.banksteel.openerp.commons.mongoDBBase.entity.Pager;
import com.banksteel.openerp.commons.mongoDBBase.entity.SerializeQuery;
/**
* @description:建立公共的BaseDao接口,所有的Dao都需要继承这个类
* @projectName:openerp-commons
* @className:MongoBaseDao.java
* @author:
* @createTime:2017年5月31日 下午5:15:49
* @version 1.0
*/
public interface MongoBaseDao<T> {
/**
* 通过条件查询实体(集合)
*
* @param query
*/
public List<T> list(Query query) ;
/**
* 获取所有的数据
* @return
*/
public List<T> list() ;
/**
* 通过一定的条件查询一个实体
*
* @param query
* @return
*/
public T findOne(Query query) ;
/**
* 通过条件查询更新数据
*
* @param query
* @param update
* @return
*/
public void update(Query query, Update update) ;
/**
* 通过给定的对象进行更新
* @param entry
*/
public void update(T entry);
/**
* 保存一个对象到mongodb
* 使用的是mongotemplate的insert方法
*
* 添加的时候,会制动增长id
* id 必须是 int id 字段
*
* @param entity
* @return
*/
public T save(T entity) ;
/**
* 通过ID获取记录
*
* @param id
* @return
*/
public T load(String id) ;
/**
* 通过ID获取记录,并且指定了集合名(表的意思)
*
* @param id
* @param collectionName
* 集合名
* @return
*/
public T findById(Long id, String collectionName) ;
/**
* 分页查询
* @param page
* @param query
* @return
*/
//public Page<T> findPage(Page<T> page,Query query);
/**
* 求数据总和 ,根据给定的 Query查询
* @param query
* @return
*/
public long count(Query query);
/**
* 获取所有数据条数
* @return
*/
public long count();
/**
* 通过id删除数据
* @param id
*/
public void delete(int id);
/**
* 一次删除多条数据
* @param ids
*/
public void deletes(int [] ids);
/**
* 通过传递过来的 对象来删除数据
* @param entry
*/
public void delete(T entry);
/**
* 带分页查询
* @return
*/
// public Pager<T> queryByPager();
/**
* 不带分页的查询方法
* @param query
* @return
*/
public Pager<T> queryByPager(SerializeQuery query);
}
5.MongoBaseDaoImpl.java
package com.banksteel.openerp.commons.mongoDBBase.dao.daoImpl;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
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.banksteel.openerp.commons.mongoDBBase.dao.MongoBaseDao;
import com.banksteel.openerp.commons.mongoDBBase.entity.Pager;
import com.banksteel.openerp.commons.mongoDBBase.entity.SerializeQuery;
import com.banksteel.openerp.commons.mongoDBBase.entity.SystemContext;
/**
* @description:这个BaseDaoImpl实现了MongoDb大部分有用的方法
* @projectName:openerp-commons
* @className:MongoBaseDaoImpl.java
* @author:
* @createTime:2017年5月31日 下午5:16:22
* @version 1.0
*/
public abstract class MongoBaseDaoImpl<T> implements MongoBaseDao<T> {
private Class<T> clazz;
// 获取我们的class对象
private Class<T> getClazz() {
if (this.clazz == null) {
ParameterizedType type = (ParameterizedType) getClass()
.getGenericSuperclass();
this.clazz = ((Class) type.getActualTypeArguments()[0]);
}
return this.clazz;
}
/**
* spring mongodb 集成操作类
*/
public abstract MongoTemplate getMongoTemplate();
public List<T> list(Query query) {
return getMongoTemplate().find(query, this.getClazz());
}
public T findOne(Query query) {
return getMongoTemplate().findOne(query, this.getClazz());
}
public void update(Query query, Update update) {
getMongoTemplate().findAndModify(query, update, this.getClazz());
}
/**
* 添加实体
*/
public T save(T entity) {
try {
// save方法会便利表单,如果存在就会更新
// mongoTemplate.save(entity);
// insert 方法不需要遍历表单
// 通过Query获取长度
// long coun = mongoTemplate.count(query, this.getClazz());
// 通过DBCollection获取数据长度
// long count =
// mongoTemplate.getCollection(mongoTemplate.getCollectionName(getClazz())).count();
this.getId();
this.getClazz().getMethod("setId", String.class)
.invoke(entity, this.getId()+"");
//这个地方有点问题,我们如果查询的数据的数目和最大id小的问题
// 获取对象,然后加上id
getMongoTemplate().insert(entity);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
return entity;
}
/**
* 通过id来加载数据对象
*/
public T load(String id) {
return getMongoTemplate().findById(id, this.getClazz());
}
/**
* 通过id来查找我们的数据对象
*/
public T findById(Long id, String collectionName) {
return getMongoTemplate().findById(id, this.getClazz(), collectionName);
}
/**
* 这个是通过Query查询
*/
public long count(Query query) {
return getMongoTemplate().count(query, this.getClazz());
}
/**
* 获取本集合中的条数
*/
public long count() {
return count(new Query());
}
// update就像一个 集合一样,添加数据
public void delete(int id) {
getMongoTemplate().remove(new Query(Criteria.where("_id").is(id)),
this.getClazz());
}
/**
* 直接删除传递过来的实体对象
*/
public void delete(T entry) {
getMongoTemplate().remove(entry);
}
/**
* 更新我们的实体类
*/
public void update(T entry) {
try {
// 更新操作,我们需要先获取到我们的 id 获取到数据库中的数据 ,然后更新
// int id =
// Integer.parseInt(this.getClazz().getDeclaredMethod("getId").invoke(entry).toString());
// System.out.println(id);
// 通过BeanUtils直接过去数据
int id = Integer.parseInt(BeanUtils.getProperty(entry, "id")
.toString());
// 获取所有的字段,然后设定到update中
// 将所有获取的数据 放下Update中
Update update = new Update();
Field[] fields = this.getClazz().getDeclaredFields();
for (Field field : fields) {
String fieldName = field.getName();
// 其中我们不能将 id这个属性添加到里面,因为id是不可以更新的
if (fieldName != null && !"id".equals(fieldName)) {
// 使用set更新器,如果没有就会添加,有就会更新
update.set(fieldName,
BeanUtils.getProperty(entry, fieldName));
}
}
// 然后更新我们的对象
this.getMongoTemplate().updateFirst(
new Query(Criteria.where("_id").is(id)), update,
this.getClazz());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* 删除多条数据
*/
public void deletes(int[] ids) {
for (int id : ids) {
delete(id);
}
}
/**
* 获取集合中所有的数据
*/
public List<T> list() {
return this.getMongoTemplate().findAll(getClazz());
}
/**
* queryByPager()方法的重载
*/
// public Pager<T> queryByPager() {
// SerializeQuery query = Query.query(Criteria.where("").is(""));
// return this.queryByPager(query);
// }
public Pager<T> queryByPager(SerializeQuery query) {
// 获取页面的大小和 页面
Integer pageSize = query.getNumPerPage();
Integer pageNow = query.getCurrentPage();
String order = SystemContext.getOrder();
String sort =SystemContext.getSort();
//获取条数,由于不同的条件,所产生的条数是不一样的
int count = Integer.parseInt(this.count(query) + "");
Sort mySort = null;
// 每页显示默认为10条数据
if (pageSize == null || pageSize <= 0) {
pageSize = 10;
}
if (pageNow == null || pageNow < 0) {
pageNow = 1;
}
if(order == null || "".equals(order.trim())){
order = "lastAccess";
}
int offset = (pageNow - 1) * pageSize;
// 页面大小是多少
query.limit(pageSize);
// 从多少条开始
query.skip(offset);
//通过Sort这个 类可以完成排序的问题
if(sort != null && sort.equals("asc")){
mySort = new Sort(Direction.ASC,order);
}else{
mySort = new Sort(Direction.DESC,order); //默认降序
}
//设定排序
query.with(mySort);
List<T> datas = getMongoTemplate().find(query, getClazz());
// 设定数据
Pager<T> pager = new Pager<T>();
pager.setNumPerPage(pageSize);
pager.setCurrentPage(pageNow);
//设定页面的数
pager.setPageCount((count-1)/pageSize+1);
pager.setTotalCount(count);
pager.setRecordList(datas);
return pager;
}
/**
* 获取集合中的最大的id ,解决不能自动增长的问题
* @return
*/
private String getId(){
try {
int counts = Integer.parseInt(this.count()+"");
int lastId = 0;
//查询最后一条数据
Query query = new Query();
query.limit(1);
query.skip(counts-1);
List<T> objs = getMongoTemplate().find(query, getClazz());
if(objs != null && objs.size() >0){
Object obj = objs.get(0);
lastId = Integer.parseInt(BeanUtils.getProperty(obj, "id")+"");
}
return lastId+1+"";
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
}
6.AdminRecordLogDAO.java 用来继承上面的到
package com.banksteel.openerp.log.provider.dao;
import com.banksteel.openerp.commons.mongoDBBase.dao.MongoBaseDao;
import com.banksteel.openerp.log.api.entity.AdminRecordLog;
public interface AdminRecordLogDAO extends MongoBaseDao<AdminRecordLog> {
}
7.AdminRecordLogDAOImpl.java
package com.banksteel.openerp.log.provider.dao.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import com.banksteel.openerp.commons.mongoDBBase.dao.daoImpl.MongoBaseDaoImpl;
import com.banksteel.openerp.log.api.entity.AdminRecordLog;
import com.banksteel.openerp.log.provider.dao.AdminRecordLogDAO;
@Repository(value = "adminRecordLogDAO")
public class AdminRecordLogDAOImpl extends MongoBaseDaoImpl<AdminRecordLog> implements AdminRecordLogDAO {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public MongoTemplate getMongoTemplate()
{
return mongoTemplate;
}
}
8.MongoBaseService.java
package com.banksteel.openerp.commons.mongoDBBase.service;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.banksteel.openerp.commons.mongoDBBase.entity.MongoBaseEntity;
import com.banksteel.openerp.commons.mongoDBBase.entity.MongoSearchCondition;
import com.banksteel.openerp.commons.mongoDBBase.entity.Pager;
import com.banksteel.openerp.commons.mongoDBBase.entity.SerializeQuery;
public interface MongoBaseService<T extends MongoBaseEntity, P extends Exception>
{
/**
* 通过条件查询实体(集合)
*
* @param query
*/
public List<T> findByCondition(Query query) ;
/**
* 获取所有的数据
* @return
*/
public List<T> findAll() ;
/**
* 通过一定的条件查询一个实体 ,返回满足条件的第一条
*
* @param query
* @return
*/
public T findOne(Query query) ;
/**
* 通过条件查询更新数据
*
* @param query
* @param update
* @return
*/
public void update(Query query, Update update) throws P;
/**
* 通过给定的对象进行更新
* @param entry
*/
public void update(T entry) throws P;
/**
* 保存一个对象到mongodb
* 使用的是mongotemplate的insert方法
*
* 添加的时候,会制动增长id
* id 必须是 int id 字段
*
* @param entity
* @return
*/
public T create(T entity) throws P;
/**
* 通过ID获取记录
*
* @param id
* @return
*/
public T findById(String id) ;
/**
* 通过ID获取记录,并且指定了集合名(表的意思)
*
* @param id
* @param collectionName
* 集合名
* @return
*/
public T findById(Long id, String collectionName) ;
/**
* 分页查询
* @param page
* @param query
* @return
*/
//public Page<T> findPage(Page<T> page,Query query);
/**
* 求数据总和 ,根据给定的 Query查询
* @param query
* @return
*/
public long count(Query query);
/**
* 获取所有数据条数
* @return
*/
public long count();
/**
* 通过id删除数据
* @param id
*/
public void delete(int id) throws P;
/**
* 一次删除多条数据
* @param ids
*/
public void deletes(int [] ids) throws P;
/**
* 通过传递过来的 对象来删除数据
* @param entry
*/
public void delete(T entry) throws P;
/**
* 带分页查询
* @return
*/
// public Pager<T> queryByPager();
/**
* 不带分页的查询方法
* @param query
* @return
*/
public Pager<T> queryByPager(MongoSearchCondition mongoSearchCondition);
}
9.MongoBaseServiceImpl.java
package com.banksteel.openerp.commons.mongoDBBase.service.impl;
import java.util.List;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import com.banksteel.openerp.commons.filter.SaasParameter;
import com.banksteel.openerp.commons.mongoDBBase.MongoObjectAnalyze;
import com.banksteel.openerp.commons.mongoDBBase.dao.MongoBaseDao;
import com.banksteel.openerp.commons.mongoDBBase.entity.MongoBaseEntity;
import com.banksteel.openerp.commons.mongoDBBase.entity.MongoSearchCondition;
import com.banksteel.openerp.commons.mongoDBBase.entity.Pager;
import com.banksteel.openerp.commons.mongoDBBase.service.MongoBaseService;
public abstract class MongoBaseServiceImpl<T extends MongoBaseEntity, P extends Exception> implements MongoBaseService<T, P>
{
public abstract MongoBaseDao<T> getDao();
@Override
public List<T> findByCondition(Query query)
{
return getDao().list(query);
}
@Override
public List<T> findAll()
{
return getDao().list();
}
@Override
public T findOne(Query query)
{
return getDao().findOne(query);
}
@Override
public void update(Query query, Update update) throws P
{
getDao().update(query, update);
}
@Override
public void update(T entry) throws P
{
getDao().update(entry);
}
@Override
public T create(T entity) throws P
{
String memberId = SaasParameter.getMemberId();
entity.setMemberId(memberId);
return getDao().save(entity);
}
@Override
public T findById(String id)
{
return getDao().load(id);
}
@Override
public T findById(Long id, String collectionName)
{
return getDao().findById(id, collectionName);
}
@Override
public long count(Query query)
{
return getDao().count(query);
}
@Override
public long count()
{
return getDao().count();
}
@Override
public void delete(int id) throws P
{
getDao().delete(id);
}
@Override
public void deletes(int[] ids) throws P
{
getDao().deletes(ids);
}
@Override
public void delete(T entry) throws P
{
getDao().delete(entry);
}
// @Override
// public Pager<T> queryByPager()
// {
// return getDao().queryByPager();
// }
@Override
public Pager<T> queryByPager(MongoSearchCondition mongoSearchCondition)
{
return getDao().queryByPager(MongoObjectAnalyze.analyzeField(mongoSearchCondition));
}
}
10.AdminRecordLogService.java
package com.banksteel.openerp.log.api.service;
import com.banksteel.openerp.commons.mongoDBBase.service.MongoBaseService;
import com.banksteel.openerp.log.api.entity.AdminRecordLog;
import com.banksteel.openerp.log.api.exception.AdminRecordLogException;
public interface AdminRecordLogService extends MongoBaseService<AdminRecordLog, AdminRecordLogException> {
}
11.AdminRecordLogServiceImpl.java
package com.banksteel.openerp.log.provider.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Repository;
import com.banksteel.openerp.commons.mongoDBBase.dao.MongoBaseDao;
import com.banksteel.openerp.commons.mongoDBBase.service.impl.MongoBaseServiceImpl;
import com.banksteel.openerp.log.api.entity.AdminRecordLog;
import com.banksteel.openerp.log.api.exception.AdminRecordLogException;
import com.banksteel.openerp.log.api.service.AdminRecordLogService;
import com.banksteel.openerp.log.provider.dao.AdminRecordLogDAO;
@Repository(value = "adminRecordLogService")
public class AdminRecordLogServiceImpl extends MongoBaseServiceImpl<AdminRecordLog, AdminRecordLogException> implements AdminRecordLogService {
@Resource(name = "adminRecordLogDAO")
public AdminRecordLogDAO adminReocrdLogDAO;
@Override
public MongoBaseDao<AdminRecordLog> getDao()
{
return adminReocrdLogDAO;
}
}
12。AdminRecordLog.java
package com.banksteel.openerp.log.api.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import com.banksteel.openerp.commons.mongoDBBase.entity.MongoBaseEntity;
import cn.mysteel.util.DateUtils;
@Document(collection = AdminRecordLog.COLLECTION_NAME)
public class AdminRecordLog extends MongoBaseEntity
{
private static final long serialVersionUID = -1232921965512669447L;
protected static final String COLLECTION_NAME = "tbl_admin_log";
@Id
private String id;
private String memberName;
private Long operatorId;
private String operatorName;
private String operatorIp;
private String operationType;
private String businessType;
private Long operationTime;
private String logContent;
public String getBusinessType()
{
return businessType;
}
public void setBusinessType(String businessType)
{
this.businessType = businessType;
}
public String getMemberName()
{
return memberName;
}
public void setMemberName(String memberName)
{
this.memberName = memberName;
}
public Long getOperatorId()
{
return operatorId;
}
public void setOperatorId(Long operatorId)
{
this.operatorId = operatorId;
}
public String getOperatorName()
{
return operatorName;
}
public void setOperatorName(String operatorName)
{
this.operatorName = operatorName;
}
public String getOperatorIp()
{
return operatorIp;
}
public void setOperatorIp(String operatorIp)
{
this.operatorIp = operatorIp;
}
public String getOperationType()
{
return operationType;
}
public void setOperationType(String operationType)
{
this.operationType = operationType;
}
public Long getOperationTime()
{
return operationTime;
}
public void setOperationTime(Long operationTime)
{
this.operationTime = operationTime;
}
// 自定义转换,从毫秒数转为字符串,用于dozer转换
public String getOperationTimeToString()
{
if (operationTime != null && operationTime > 0)
{
return DateUtils.formatDate(operationTime, "yyyy-MM-dd HH:mm:ss");
}
else
{
return null;
}
}
public String getLogContent()
{
return logContent;
}
public void setLogContent(String logContent)
{
this.logContent = logContent;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public void setVersion(Integer version)
{
if (version == null)
{
version = super.getVersion() + 1;
}
super.setVersion(version);
}
}
13.
AdminRecordLog adminLog = new AdminRecordLog();
adminLog.setMemberId(memberId.toString());
adminLog.setMemberName(StringUtils.isEmpty(log[2].replace("null", "")) ? "" : log[2]);
adminLog.setOperatorId(userId);
adminLog.setOperatorName(event.getMDCPropertyMap().get("operator_name"));
adminLog.setOperatorIp(event.getMDCPropertyMap().get("operator_ip"));
adminLog.setOperationType(log[3]);
adminLog.setBusinessType(log[4]);
adminLog.setOperationTime(event.getTimeStamp());
adminLog.setLogContent(log[5]);
try {
SaasParameter.setMemberId("-1");
adminRecordLogService.create(adminLog);
} catch (Exception e) {
System.err.println("生成日志失败");
e.printStackTrace();
}
14.整体流程就这样,也有dao,service。方法跟调用数据库一样,只是换了MongoDB。