Get the App
SLTechnology News&Howtos  ›  Database  › 

Spring4.3.7 integrates mongodb3.2.1

Shulou Source: shulou.com Published: 2022-06-01 17:45:51 10月03日 Update

A few days ago, I wrote a mongodb native utility class, refer to "http://ylcodes01.blog.51cto.com/5607366/1933342""

The project needs to be distributed, so now integrated into spring, today combined with spring-mongodb to write some commonly used tools.

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;@Repositorypublic 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;// primary key private String interfaceMethod;// interface method name private String businessName;// business name private String clientReqParams;// client request parameter private String serviceRepParams;// server response parameter private String logInfo / / Log content: private Long clientReqTime;// client call time, such as exception, private Long serviceRepTime;// server response time, private Long duration;// duration, private String clientReqIpPort;// client request IP and PORT private String serviceRepIpPort;// server response IP and PORT private String ifSuccess;// service call are identified successfully, 1 success 2 failed private Long createTime / / insert time 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;@Componentpublic 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;@Componentpublic class MongoObjectParams {private String javaType = "java"; / * get the query parameter * * @ 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.Timestimport 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.234mongo.port=10143

Spring-mongodb.xml

# what you should pay attention to in spring-mongodb.xml above: since you are using the mongodb3.X version,

Don't use the mongo:mongo tag. Change it to mongo:mongo-client. Some parameters need to be changed.

Take a specific look at the source code and documentation.

Possible errors are as follows:

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; / * get entities based on primary key * / @ Test public void testFindOne () {MongoEntity mongoEntity = mongoEntityDao.getMongoEntityById ("593e3f8ba4977227581b398c"); System.out.println (mongoEntity) } / * get the collection list according to filter criteria * / @ 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);}} / * get the number of queries according to filter conditions * / @ Test public void testFindCount () {Query query = new Query (); query.addCriteria (new Criteria ("InterfaceMethod"). Nin ("InterfaceMethod5")) System.out.println (mongoEntityDao.findCount (query));} / * get the paging collection according to the filter criteria * skip: starting with the article, but excluding this data * limit: several pieces of data per page * / @ Test public void testFindList () {Query query = new Query (); query.addCriteria (new Criteria ("InterfaceMethod"). Nin ("InterfaceMethod11")) List list = mongoEntityDao.findList; for (MongoEntity mongoEntity: list) {System.out.println (mongoEntity.getBusinessName ());}} / * * New entity * / @ 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 ()) } / * Delete entity objects * / @ Test public void testRemove () {MongoEntity mongoEntity = mongoEntityDao.findOne ("593e4f1ca4977223d8f705aa"); System.out.println (mongoEntity); mongoEntityDao.remove (mongoEntity); mongoEntity = mongoEntityDao.findOne ("593e4f1ca4977223d8f705aa"); System.out.println (mongoEntity) } / * Delete the corresponding data by filtering conditions and entity objects * / @ 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 (the project name in the picture is not the same as the project name in the pom.xml below, just modify it)

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 1.6 UTF -8 maven-surefire-plugin 2.12.4 * * / * Tests.java org.apache.maven.plugins maven-resources-plugin 2.6 UTF-8

# the above pom.xml must pay attention to one problem:

When the above org.hibernate.version configuration is changed from 5.0.2.Final to 5.4.1Final, one more configuration is required, as follows:

2.2.4 org.glassfish.webjavax.el$ {javax.el-version}

Otherwise, the error may be as follows:

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. (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

Tags: Parameters entity time condition service customer client data project UTF-8 success name object tool query configuration consistency business number content Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Linux Huawei Docker vpn