BaseMongoDao
package com.stbr.common.mongodb.base;
import com.mongodb.WriteResult;
import com.stbr.common.mongodb.util.MongoFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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 java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
public class BaseMongoDao implements IBaseMongoDao{
private Class clazz;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private MongoFactory mongoFactory;
public BaseMongoDao() {
ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
clazz = (Class) parameterizedType.getActualTypeArguments()[0];
}
@Override
public void insert(T entity) {
mongoTemplate.insert(entity);
}
@Override
public T findOne(String id) {
Query query = new Query();
query.addCriteria(new Criteria("_id").is(id));
return getMongoTemplate().findOne(query,clazz);
}
@Override
public List find(Query query) {
return getMongoTemplate().find(query,clazz);
}
@Override
public Long findCount(Query query) {
return getMongoTemplate().count(query,clazz);
}
@Override
public List findList(Integer skip, Integer limit,Query query) {
query.with(new Sort(new Sort.Order(Sort.Direction.ASC,"createTime")));
query.skip(skip).limit(limit);
return find(query);
}
@Override
public Integer update(Query query, Update update) throws Exception {
WriteResult writeResult = getMongoTemplate().updateFirst(query,update,clazz);
return (null == writeResult ? 0 : writeResult.getN());
}
@Override
public Integer update(T entity) throws Exception {
Map map = mongoFactory.converObjectToParams(entity);
Query query = new Query();
query.addCriteria(new Criteria("_id").is(map.get("id")));
Update update = (Update) map.get("update");
return this.update(query,update);
}
@Override
public Integer remove(T entity) {
WriteResult writeResult = getMongoTemplate().remove(entity);
return (null == writeResult ? 0 : writeResult.getN());
}
@Override
public Integer remove(Query query, T entity) {
WriteResult writeResult = getMongoTemplate().remove(query,entity.getClass());
return (null == writeResult ? 0 : writeResult.getN());
}
public MongoTemplate getMongoTemplate(){
return mongoTemplate;
}
}
IBaseMongoDao
package com.stbr.common.mongodb.base;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;
public interface IBaseMongoDao {
public T findOne(String id);
public List find(Query query);
public Long findCount(Query query);
public List findList(Integer skip,Integer limit,Query query);
public void insert(T entity);
public Integer update(Query query, Update update) throws Exception;
public Integer update(T entity) throws Exception;
public Integer remove(T entity);
public Integer remove(Query query,T entity);
}
IMongoEntityDao
package com.stbr.common.mongodb.dao;
import com.stbr.common.mongodb.base.IBaseMongoDao;
import com.stbr.common.mongodb.model.MongoEntity;
public interface IMongoEntityDao extends IBaseMongoDao{
public MongoEntity getMongoEntityById(String id);
}
MongoEntityDao
package com.stbr.common.mongodb.dao;
import com.stbr.common.mongodb.base.BaseMongoDao;
import com.stbr.common.mongodb.model.MongoEntity;
import org.springframework.stereotype.Repository;
@Repository
public class MongoEntityDao extends BaseMongoDao implements IMongoEntityDao{
@Override
public MongoEntity getMongoEntityById(String id) {
MongoEntity mongoEntity = findOne(id);
return mongoEntity;
}
}
MongoEntity
package com.stbr.common.mongodb.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "mongoLogInfo")
public class MongoEntity {
@Id
private String id;//主键
private String interfaceMethod;//接口方法名称
private String businessName;//业务名称
private String clientReqParams;//客户端请求参数
private String serviceRepParams;//服务端响应参数
private String logInfo;//日志内容:包括异常等
private Long clientReqTime;//客户端调用时间
private Long serviceRepTime;//服务端响应时间
private Long duration;//持续时间
private String clientReqIpPort;//客户端请求IP和PORT
private String serviceRepIpPort;//服务端响应IP和PORT
private String ifSuccess;//服务调用是否成功标识,1成功2失败
private Long createTime;//插入时间
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInterfaceMethod() {
return interfaceMethod;
}
public void setInterfaceMethod(String interfaceMethod) {
this.interfaceMethod = interfaceMethod;
}
public String getBusinessName() {
return businessName;
}
public void setBusinessName(String businessName) {
this.businessName = businessName;
}
public String getClientReqParams() {
return clientReqParams;
}
public void setClientReqParams(String clientReqParams) {
this.clientReqParams = clientReqParams;
}
public String getServiceRepParams() {
return serviceRepParams;
}
public void setServiceRepParams(String serviceRepParams) {
this.serviceRepParams = serviceRepParams;
}
public String getLogInfo() {
return logInfo;
}
public void setLogInfo(String logInfo) {
this.logInfo = logInfo;
}
public Long getClientReqTime() {
return clientReqTime;
}
public void setClientReqTime(Long clientReqTime) {
this.clientReqTime = clientReqTime;
}
public Long getServiceRepTime() {
return serviceRepTime;
}
public void setServiceRepTime(Long serviceRepTime) {
this.serviceRepTime = serviceRepTime;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public String getClientReqIpPort() {
return clientReqIpPort;
}
public void setClientReqIpPort(String clientReqIpPort) {
this.clientReqIpPort = clientReqIpPort;
}
public String getServiceRepIpPort() {
return serviceRepIpPort;
}
public void setServiceRepIpPort(String serviceRepIpPort) {
this.serviceRepIpPort = serviceRepIpPort;
}
public String getIfSuccess() {
return ifSuccess;
}
public void setIfSuccess(String ifSuccess) {
this.ifSuccess = ifSuccess;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
}
MongoFactory
package com.stbr.common.mongodb.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
@Component
public class MongoFactory {
@Autowired
private MongoObjectParams objectParams;
public Map converObjectToParams(Object object) throws Exception {
Map map = new HashMap();
Update update = new Update();
Map params = objectParams.createParams(object);
String id = params.get("id");
Set> sets = params.entrySet();
Iterator> iteratos = sets.iterator();
while(iteratos.hasNext()){
Map.Entry entry = iteratos.next();
String key = entry.getKey();
String value = entry.getValue();
if(!key.equals("id")){
update.set(key,value);
}
}
map.put("id",id);
map.put("update",update);
return map;
}
}
MongoObjectParams
package com.stbr.common.mongodb.util;
import org.springframework.stereotype.Component;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
@Component
public class MongoObjectParams {
private String javaType = "java";
/**
* 获取查询的参数
*
* @param object
* @return
* @throws Exception
*/
public Map createParams(Object object) throws Exception {
Map params = new HashMap();
setIntoParams(params,object, null);
return params;
}
private void setIntoParams(Map params,Object object, String fatherName) throws IllegalAccessException,
Exception {
Field[] fields = object.getClass().getDeclaredFields();
for (Field file : fields) {
boolean accessFlag = file.isAccessible();
file.setAccessible(true);
String name = file.getName();
Object value = file.get(object);
if(file.getType().getName().equals("java.lang.Class")){
break;
}else if(file.getType().getName().contains(javaType)){
if(fatherName != null && !fatherName.equals(" ")){
name = fatherName+"."+name;
}
if(value != null){
params.put(name, value+"");
}
}else{
if(value != null){
setIntoParams(params,file.get(object), name);
}
}
file.setAccessible(accessFlag);
}
}
}
MongoTimestampConverter
package com.stbr.common.mongodb.util;
import org.springframework.core.convert.converter.Converter;
import java.sql.Timestamp;
import java.util.Date;
public class MongoTimestampConverter implements Converter {
@Override
public Timestamp convert(Date date) {
if(null != date){
return new Timestamp(date.getTime());
}
return null;
}
}
mongo.properties
mongo.host=192.168.200.234
mongo.port=10143
spring-mongodb.xml
#上述spring-mongodb.xml要注意的地方:由于现在用的是mongodb3.X版本,所以
就不要使用mongo:mongo标签了,要改成mongo:mongo-client,一些参数要改变了,
具体看下源码和文档即可。
可能报错如下:
mongo-options' is no longer supported for MongoDB
MongdbTestpackage com.stbr.common.mongodb.test;
import com.stbr.common.mongodb.dao.IMongoEntityDao;
import com.stbr.common.mongodb.model.MongoEntity;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.Date;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring-mongodb.xml")
public class MongdbTest {
@Autowired
private IMongoEntityDao mongoEntityDao;
/**
* 根据主键获取实体
*/
@Test
public void testFindOne(){
MongoEntity mongoEntity = mongoEntityDao.getMongoEntityById("593e3f8ba4977227581b398c");
System.out.println(mongoEntity);
}
/**
* 根据过滤条件获取集合列表
*/
@Test
public void testFind(){
Query query = new Query();
List list1 = mongoEntityDao.find(query);
System.out.println(list1.size());
query = new Query();
query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod5"));
List list2 = mongoEntityDao.find(query);
for(MongoEntity mongoEntity : list2){
System.out.println(mongoEntity);
}
}
/**
* 根据过滤条件获取查询个数
*/
@Test
public void testFindCount(){
Query query = new Query();
query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod5"));
System.out.println(mongoEntityDao.findCount(query));
}
/**
* 根据过滤条件获取分页集合
* skip:从第几条开始,但不包括这条数据
* limit:每页几条数据
*/
@Test
public void testFindList(){
Query query = new Query();
query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod11"));
List list = mongoEntityDao.findList(10,5,query);
for(MongoEntity mongoEntity : list){
System.out.println(mongoEntity.getBusinessName());
}
}
/**
* 实体新增
*/
@Test
public void testInsert(){
for(int i = 7; i < 30 ; i++){
MongoEntity mongoEntity = new MongoEntity();
mongoEntity.setInterfaceMethod("InterfaceMethod" + i);
mongoEntity.setBusinessName("BusinessName" + i);
mongoEntity.setClientReqIpPort("ClientReqIpPort" + i);
mongoEntity.setServiceRepIpPort("ServiceRepIpPort" + i);
mongoEntity.setLogInfo("LogInfo" + i);
Long time1 = new Date().getTime();
mongoEntity.setClientReqTime(time1);
Long time2 = new Date().getTime();
mongoEntity.setServiceRepTime(time2);
mongoEntity.setDuration(time2 - time1);
mongoEntity.setClientReqIpPort("ClientReqIpPort" + i);
mongoEntity.setServiceRepIpPort("ServiceRepIpPort" + i);
mongoEntity.setIfSuccess("1");
mongoEntity.setCreateTime(new Date().getTime());
mongoEntityDao.insert(mongoEntity);
}
}
/**
* 通过传入的实体ID更新实体中的其他内容
* @throws Exception
*/
@Test
public void testUpdateEntity() throws Exception{
MongoEntity mongoEntity = mongoEntityDao.findOne("593e3f8ba4977227581b398c");
System.out.println("1------------->" + mongoEntity.getBusinessName());
mongoEntity.setBusinessName("setBusinessNametest");
mongoEntityDao.update(mongoEntity);
mongoEntity = mongoEntityDao.findOne("593e3f8ba4977227581b398c");
System.out.println("2------------->" + mongoEntity.getBusinessName());
}
/**
* 删除实体对象
*/
@Test
public void testRemove(){
MongoEntity mongoEntity = mongoEntityDao.findOne("593e4f1ca4977223d8f705aa");
System.out.println(mongoEntity);
mongoEntityDao.remove(mongoEntity);
mongoEntity = mongoEntityDao.findOne("593e4f1ca4977223d8f705aa");
System.out.println(mongoEntity);
}
/**
* 通过过滤条件和实体对象删除对应数据
*/
@Test
public void testRemoveByQuery(){
Query query = new Query();
query.addCriteria(new Criteria("_id").is("593e4f1ca4977223d8f705a3"));
MongoEntity entity = new MongoEntity();
System.out.println(mongoEntityDao.remove(query,entity));
}
}
pom.xml(图片中的项目名和下述的pom.xml中的项目名不一致,修改下即可)
4.0.0
TestSpringMongo3
TestSpringMongo3
war
1.0-SNAPSHOT
TestSpringMongo3 Maven Webapp
nexus-repos
Team Nexus Repository
http://192.168.200.205:8081/nexus/content/groups/public/
true
true
nexus-repos
Team Nexus Repository
http://192.168.200.205:8081/nexus/content/groups/public/
true
true
${project.build.directory}/endorsed
UTF-8
7.0
3.1.0
1.2
1.2.16
1.7.1
4.12
2.1
4.3.7.RELEASE
1.10.4.RELEASE
3.4.2
1.1.0.Final
5.0.2.Final
junit
junit
${junit.version}
test
javax
javaee-web-api
${javax.version}
provided
javax.servlet
jstl
${javax.servlet.jstl.version}
runtime
javax.servlet
javax.servlet-api
${javax.servlet.version}
org.slf4j
slf4j-jdk14
${org.slf4j.version}
log4j
log4j
${log4j.version}
org.htmlparser
htmlparser
${org.htmlparser.version}
org.springframework
spring-aop
${org.springframework.version}
org.springframework
spring-context-support
${org.springframework.version}
org.springframework
spring-beans
${org.springframework.version}
org.springframework
spring-context
${org.springframework.version}
org.springframework
spring-core
${org.springframework.version}
org.springframework
spring-expression
${org.springframework.version}
org.springframework
spring-web
${org.springframework.version}
org.springframework
spring-webmvc
${org.springframework.version}
org.springframework
spring-test
${org.springframework.version}
test
org.springframework.data
spring-data-mongodb
${spring-data-mongodb.version}
javax.validation
validation-api
${javax.validation.version}
org.hibernate
hibernate-validator
${org.hibernate.version}
TestSpringMongo3
src/main/java
**/*.xml
**/*.properties
false
src/main/resources
**/*.xml
**/*.properties
false
maven-compiler-plugin
2.5.1
1.6
UTF-8
maven-surefire-plugin
2.12.4
**/*Tests.java
org.apache.maven.plugins
maven-resources-plugin
2.6
UTF-8
#上述pom.xml一定要注意一个问题:
当上述org.hibernate.version配置为5.0.2.Final改成5.4.1Final时,那么要多一个配置,如下:
2.2.4
org.glassfish.web
javax.el
${javax.el-version}
不然,也许会报错如下:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0': Invocation of init method failed; nested exception is javax.validation.ValidationException: HV000183: Unable to initialize 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead
Caused by: javax.validation.ValidationException: HV000183: Unable to initialize 'javax.el.ExpressionFactory'. Check that you have the EL dependencies on the classpath, or use ParameterMessageInterpolator instead
at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.buildExpressionFactory(ResourceBundleMessageInterpolator.java:102)
at org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator.
at org.hibernate.validator.internal.engine.ConfigurationImpl.getDefaultMessageInterpolator(ConfigurationImpl.java:423)
Caused by: javax.el.ELException: Provider com.sun.el.ExpressionFactoryImpl not found
Caused by: java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl