您好,登录后才能下订单哦!
前几天写了个mongodb原生的工具类,参考“http://ylcodes01.blog.51cto.com/5607366/1933342”,
项目里需要做分布式,所以现在集成到spring中,今天结合spring-mongodb写了一些常用的工具。
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<T> implements IBaseMongoDao<T>{ private Class<T> clazz; @Autowired private MongoTemplate mongoTemplate; @Autowired private MongoFactory mongoFactory; public BaseMongoDao() { ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass(); clazz = (Class<T>) 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<T> find(Query query) { return getMongoTemplate().find(query,clazz); } @Override public Long findCount(Query query) { return getMongoTemplate().count(query,clazz); } @Override public List<T> 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<String,Object> 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<T> { public T findOne(String id); public List<T> find(Query query); public Long findCount(Query query); public List<T> 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<MongoEntity>{ 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<MongoEntity> 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<String,Object> converObjectToParams(Object object) throws Exception { Map<String,Object> map = new HashMap<String,Object>(); Update update = new Update(); Map<String,String> params = objectParams.createParams(object); String id = params.get("id"); Set<Map.Entry<String,String>> sets = params.entrySet(); Iterator<Map.Entry<String,String>> iteratos = sets.iterator(); while(iteratos.hasNext()){ Map.Entry<String,String> 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<String, String> createParams(Object object) throws Exception { Map<String, String> params = new HashMap<String, String>(); setIntoParams(params,object, null); return params; } private void setIntoParams(Map<String, String> 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<Date,Timestamp> { @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
<?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-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.10.xsd"> <!-- 不引入这个导致test中的注入不成功 --> <context:component-scan base-package="com.stbr.common" /> <context:property-placeholder location="classpath:mongo.properties"/> <mongo:mongo-client host="${mongo.host}" port="${mongo.port}" id="mongo"> <mongo:client-options write-concern="SAFE" /> </mongo:mongo-client> <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 --> <mongo:db-factory dbname="runoob" mongo-ref="mongo" id="mongoDbFactory"/> <bean id="mappingContext" class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" /> <!-- 默认Mongodb类型映射 --> <bean id="defaultMongoTypeMapper" class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper"> <constructor-arg name="typeKey"> <null /><!-- 这里设置为空,可以把 spring data mongodb 多余保存的_class字段去掉 --> </constructor-arg> </bean> <!-- 转换器:1、去掉write的_class字段 2、TimestampConverter --> <mongo:mapping-converter id="mongoConverter" base-package="com.stbr.common.mongodb.util" type-mapper-ref="defaultMongoTypeMapper"> <mongo:custom-converters> <mongo:converter> <bean class="com.stbr.common.mongodb.util.MongoTimestampConverter" /> </mongo:converter> </mongo:custom-converters> </mongo:mapping-converter> <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 --> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> <constructor-arg name="mongoConverter" ref="mongoConverter" /> </bean> <context:annotation-config /> </beans>
#上述spring-mongodb.xml要注意的地方:由于现在用的是mongodb3.X版本,所以
就不要使用mongo:mongo标签了,要改成mongo:mongo-client,一些参数要改变了,
具体看下源码和文档即可。
可能报错如下:
mongo-options' is no longer supported for MongoDB
MongdbTest
package 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.SpringJUnit4Cla***unner; import java.util.Date; import java.util.List; @RunWith(SpringJUnit4Cla***unner.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<MongoEntity> list1 = mongoEntityDao.find(query); System.out.println(list1.size()); query = new Query(); query.addCriteria(new Criteria("InterfaceMethod").nin("InterfaceMethod5")); List<MongoEntity> 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<MongoEntity> 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中的项目名不一致,修改下即可)
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>TestSpringMongo3</groupId> <artifactId>TestSpringMongo3</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>TestSpringMongo3 Maven Webapp</name> <!-- 设定主仓库 --> <repositories> <!-- nexus私服 --> <repository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://192.168.200.205:8081/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <!-- 设定插件仓库 --> <pluginRepositories> <pluginRepository> <id>nexus-repos</id> <name>Team Nexus Repository</name> <url>http://192.168.200.205:8081/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <properties> <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 设置变量:用于统一管理Library的版本 --> <javax.version>7.0</javax.version> <javax.servlet.version>3.1.0</javax.servlet.version> <javax.servlet.jstl.version>1.2</javax.servlet.jstl.version> <log4j.version>1.2.16</log4j.version> <org.slf4j.version>1.7.1</org.slf4j.version> <junit.version>4.12</junit.version> <org.htmlparser.version>2.1</org.htmlparser.version> <org.springframework.version>4.3.7.RELEASE</org.springframework.version> <spring-data-mongodb.version>1.10.4.RELEASE</spring-data-mongodb.version> <mongodb-version>3.4.2</mongodb-version> <javax.validation.version>1.1.0.Final</javax.validation.version> <org.hibernate.version>5.0.2.Final</org.hibernate.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>${javax.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>${javax.servlet.jstl.version}</version> <scope>runtime</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${javax.servlet.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>${org.slf4j.version}</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.htmlparser</groupId> <artifactId>htmlparser</artifactId> <version>${org.htmlparser.version}</version> </dependency> <!-- spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${org.springframework.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${org.springframework.version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>${spring-data-mongodb.version}</version> </dependency> <!-- javax.validation相关 --> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>${javax.validation.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>${org.hibernate.version}</version> </dependency> </dependencies> <build> <finalName>TestSpringMongo3</finalName> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.xml</include> <include>**/*.properties</include> </includes> <filtering>false</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.5.1</version> <configuration> <source>1.6</source> <target>1.6</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.12.4</version> <configuration> <includes> <include>**/*Tests.java</include> </includes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build> </project>
#上述pom.xml一定要注意一个问题:
当上述org.hibernate.version配置为5.0.2.Final改成5.4.1Final时,那么要多一个配置,如下:
<javax.el-version>2.2.4</javax.el-version> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.el</artifactId> <version>${javax.el-version}</version> </dependency>
不然,也许会报错如下:
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.<init>(ResourceBundleMessageInterpolator.java:45)
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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。