javascript
Spring整合Mongodb,Maven的依赖,Spring配置,MongoDB的公共操作类,使用SpringMVC的Controller进行测试并返回结果的案例
在和Spring和MongoDB進(jìn)行整合的時候需要如下三個jar,分別是:
spring-data-commons spring-data-mongodb mongo-java-driver |
下面講解Spring和MongoDB2.x進(jìn)行整合的Spring配置(下面案例以下面的方式進(jìn)行說明:)
Maven的Pom文件的配置如下:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.7.2.RELEASE</version> </dependency> ????? <dependency> ????? ??? <groupId>org.springframework.data</groupId> ????? ??? <artifactId>spring-data-mongodb</artifactId> ????? ??? <version>1.4.2.RELEASE</version> ????? </dependency> ????? ????? <dependency> ????? ??? <groupId>org.mongodb</groupId> ????? ??? <artifactId>mongo-java-driver</artifactId> ????? ??? <version>2.10.1</version> ????? </dependency> |
配置好Pom之后,在pom.xml所在的項(xiàng)目位置處執(zhí)行如下命令:
mvn -Pall eclipse:eclipse
?
注意:正對mongoDB3.4.2的maven的依賴配置如下:
<dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-commons</artifactId> <version>1.13.0.RELEASE</version> </dependency> ????? <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-mongodb</artifactId> <version>1.10.0.RELEASE</version> </dependency> ????? <dependency> <groupId>org.mongodb</groupId> <artifactId>mongo-java-driver</artifactId> <version>3.3.0</version> </dependency> |
如果用到分頁相關(guān)的插件,可以按照如下方式配置maven依賴
<dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> ?? ?<version>0.9.4</version> </dependency> ? <dependency> ?? <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.0.3</version> </dependency> |
?
然后到spring的配置處進(jìn)行如下配置:
<?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:p="http://www.springframework.org/schema/p" ?? xmlns:context="http://www.springframework.org/schema/context" ?? xmlns:tx="http://www.springframework.org/schema/tx" ?? xmlns:task="http://www.springframework.org/schema/task" ?? 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.1.xsd? ??? http://www.springframework.org/schema/tx?? ??? http://www.springframework.org/schema/tx/spring-tx-4.0.xsd ??? http://www.springframework.org/schema/mvc ??? http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ??? http://www.springframework.org/schema/cache ??? http://www.springframework.org/schema/cache/spring-cache-4.0.xsd ??? http://www.springframework.org/schema/task ??? http://www.springframework.org/schema/task/spring-task-4.0.xsd ??? http://www.springframework.org/schema/context?? ??? http://www.springframework.org/schema/context/spring-context-4.0.xsd ??? http://www.springframework.org/schema/aop ??? http://www.springframework.org/schema/aop/spring-aop-4.0.xsd ??? http://www.springframework.org/schema/data/mongo ??? http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> ? ??? <!-- 緩存配置 ??? <ehcache:annotation-driven cache-manager="cacheManager" />? ??? <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">? ??????? <property name="configLocation" value="classpath:ehcache.xml"/>? ??? </bean> ????<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> ????????<property name="cacheManager" ref="cacheManagerFactory" /> ????</bean> ???? --> ?? <!-- 打開注解 --> ?? <context:annotation-config /> ?? <!-- <aop:aspectj-autoproxy/> --> ?? <!-- 打開自動掃描 --> ?? <context:component-scan base-package="cn.com.hbny.docdetection" /> ?? ?? <!-- 定時器驅(qū)動 --> ?? <task:annotation-driven/> ? ?? <!-- 引入jdbc配置文件 --> ?? <context:property-placeholder location="classpath:jdbc.properties,classpath:mongodb.properties" /> ? ?? <!-- ?? 以下用于配置多數(shù)據(jù)源 ?? 配置parentDataSource的父bean,再配置多個數(shù)據(jù)源繼承這個bean,對driverClassName、 ?? url、username、password等數(shù)據(jù)源連接參數(shù)進(jìn)行各自的重寫、例如mysqlDataSource、 ?? 在DataSource bean中要注入所要切換的數(shù)據(jù)、并且設(shè)置默認(rèn)的數(shù)據(jù)源 ?? ?--> ?? <!--<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"></bean> ?? ?創(chuàng)建MySQL對應(yīng)的jdbc數(shù)據(jù)源 ?? <bean id="mysqlDataSource" parent="parentDataSource"> ????? <property name="driverClassName" value="${mysqlDriver}"></property> ????? <property name="url" value="${mysqlUrl}"></property> ????? <property name="username" value="${mysqlUsername}"></property> ????? <property name="password" value="${mysqlPassword}"></property> ?? </bean> ?? --> ?? ?? <!-- 數(shù)據(jù)源 org.apache.commons.dbcp.BasicDataSource com.alibaba.druid.pool.DruidDataSource --> ?? <bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource"> ?? ??? <!-- 初始化連接大小 --> ?? ??? <property name="initialSize" value="8" /> ?? ??? <!-- 連接池最大使用連接數(shù)量 --> ?? ??? <property name="maxActive" value="32" /> ?? ??? <!-- 連接池最小空閑 --> ?? ??? <property name="minIdle" value="4" /> ?? ??? <!-- 獲取連接最大等待時間 --> ?? ??? <property name="maxWait" value="60000" /> ?? ??? ?? ??? <!--<property name="validationQuery"><value>SELECT 1</value></property>--> ?? ??? <property name="testOnBorrow" value="false" /> ?? ??? <property name="testOnReturn" value="false" /> ?? ??? <property name="testWhileIdle" value="true" /> ?? ??? ?? ??? <!-- 配置間隔多久才進(jìn)行一次檢測,檢測需要關(guān)閉的空閑連接,單位是毫秒 --> ?? ??? <property name="timeBetweenEvictionRunsMillis" value="60000" /> ?? ??? <!-- 配置一個連接池中最小生存的時間,單位是毫秒 --> ?? ??? <property name="minEvictableIdleTimeMillis" value="25200000" /> ?? ??? ?? ??? <!-- 打開removeAbandoned功能 --> ?? ??? <property name="removeAbandoned" value="true" /> ?? ??? <!-- 1800秒,也就是30分鐘 --> ?? ??? <property name="removeAbandonedTimeout" value="1800" /> ?? ??? <!-- 關(guān)閉abanded連接時輸出錯誤日志 --> ?? ??? <property name="logAbandoned" value="true" /> ?? ??? <!-- 監(jiān)控數(shù)據(jù)庫 --> ?? ??? <property name="filters" value="mergeStat" /> ?? </bean> ?? ?? <!-- 創(chuàng)建MySQL對應(yīng)的jdbc數(shù)據(jù)源 --> ?? <bean id="mysqlDataSource" parent="parentDataSource"> ????? <property name="driverClassName" value="${mysqlDriver}"></property> ????? <property name="url" value="${mysqlUrl}"></property> ????? <property name="username" value="${mysqlUsername}"></property> ????? <property name="password" value="${mysqlPassword}"></property> ?? </bean> ? ?? <!--創(chuàng)建jdbc數(shù)據(jù)源 --> ?? <!-- <bean id="oracleDataSource" parent="parentDataSource"> ????? <property name="driverClassName" value="${oracleDriver}" /> ????? <property name="url" value="${oracleUrl}" /> ????? <property name="username" value="${oracleUsername}" /> ????? <property name="password" value="${oraclePassword}" /> ?? </bean> --> ?? ?? <!-- 注意下面的com.ucap.tpl.mapper.base.impl.DataSources是自己定義的數(shù)據(jù)源--> ?? <!-- 注意下面的cn.com.hbny.docdetection.mapper.base.impl.DataSources是自己定義的數(shù)據(jù)源--> ?? <bean id="dataSource" class="cn.com.hbny.docdetection.mapper.base.impl.DataSources"> ????? <property name="dbType" value="${dbType}"></property> ????? <property name="targetDataSources"> ???????? <map key-type="java.lang.String"> ??????????? <!-- 注意下面的key的值要和DataSourceInstances中定義的值相同--> ??????????? <entry value-ref="mysqlDataSource" key="MYSQL"></entry> ??????????? <!--<entry value-ref="oracleDataSource" key="ORACLE"></entry>--> ???????? </map> ????? </property> ????? <property name="defaultTargetDataSource" ref="mysqlDataSource"></property> ?? </bean> ? ?? <!-- 配置druid監(jiān)控spring jdbc --> ?? <bean id="druid-stat-interceptor" ??????? class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> ??? </bean> ????? ?? <!-- (事務(wù)管理)transaction manager, use JtaTransactionManager for global tx --> ?? <bean id="transactionManager" ?? ?? class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> ????? <property name="dataSource" ref="dataSource" /> ?? </bean> ?? <!-- 聲明式事務(wù) --> ?? <tx:annotation-driven transaction-manager="transactionManager" ?? ??? proxy-target-class="true"/> ? ?? <!-- 創(chuàng)建SqlSessionFactory,同時指定數(shù)據(jù)源 --> ?? <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> ????? <property name="dataSource" ref="dataSource" /> ????? <property name="configLocation" value="classpath:mybatis.xml"/> ????? <property name="mapperLocations"> ???????? <list> ???????? ??? <!-- 配置Mapper文件 --> ???????? ??? <value>classpath:sqlmaps/${dbType}/*.xml</value> ???????? </list> ????? </property> ?? </bean> ?? ?? <!-- 針對方式一 --> ?? <!-- 下面是方式1對應(yīng)的配置 --> ??? <!-- http://www.springframework.org/schema/data/mongo? ??? http://www.springframework.org/schema/data/mongo/spring-mongo.xsd --> ?? <!-- ?? <mongo:mongo host="127.0.0.1" port="27017"/> ??? <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">? ??????????? <constructor-arg ref="mongo"/>? ??????????? <constructor-arg name="databaseName" value="docdetection"/> ??? </bean> ??? --> ? ??? <!-- *******************************************方式2:開始***************************** --> ??? <!-- 方式2的配置的時候需要的配置: ??? http://www.springframework.org/schema/data/mongo ??? http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd ???? --> ??? <!-- 定義mongo對象,對應(yīng)的是mongodb官方jar包中的Mongo,replica-set設(shè)置集群副本的ip地址和端口 --> ??? <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}"> ?? ??? <!-- 一些連接屬性的設(shè)置 --> ?? ??? <mongo:options connections-per-host="${mongo.connectionsPerHost}" ?? ??? ? threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}" ?? ??? ? connect-timeout="${mongo.connectTimeout}" ?? ??? ? max-wait-time="${mongo.maxWaitTime}" ?? ??? ? auto-connect-retry="${mongo.autoConnectRetry}" ?? ??? ? socket-keep-alive="${mongo.socketKeepAlive}" ?? ??? ? socket-timeout="${mongo.socketTimeout}" ?? ??? ? slave-ok="${mongo.slaveOk}" ?? ??? ? write-number="1" ?? ??? ? write-timeout="0" ?? ??? ? write-fsync="true"/> ??? </mongo:mongo> ??? ??? <!-- mongo的工廠,通過它來取得mongo實(shí)例,dbname為mongodb的數(shù)據(jù)庫名,沒有的話會自動創(chuàng)建 --> ??? <mongo:db-factory dbname="docdetection" mongo-ref="mongo" /> ??? ??? <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> ??? ? <constructor-arg ref="mongo" /> ??? ? <constructor-arg name="databaseName" value="docdetection" /> ??? </bean> ??? ??? <!-- 映射轉(zhuǎn)換器,掃描back-package目錄下的文件,根據(jù)注釋,把它們作為mongodb的一個collection的映射 --> ??? <mongo:mapping-converter base-package="cn.com.hbny.docdetection.mongodb.beans" /> ??? <!-- mongodb bean的倉庫目錄,會自動掃描擴(kuò)展了MongoRepository接口的接口進(jìn)行注入 --> ??? <mongo:repositories base-package="cn.com.hbny.docdetection" /> ??? <!--? *******************************************方式2:結(jié)束***************************** --> ??? ??? <!-- 方式3配置 --> ??? <!-- ????????? 對應(yīng)的schema的配置如下: ??? http://www.springframework.org/schema/data/mongo ??? http://www.springframework.org/schema/data/mongo/spring-mongo-1.10.xsd ???? --> ??? <!-- mongodb 的基本配置 --> ??? <!-- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" /> --> ??? ??? <!-- <bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials"> ??????? <constructor-arg name="username" value="${userCredentials.username}"/> ??????? <constructor-arg name="password" value="${userCredentials.password}"/> ??? </bean> --> ??? ??? <!-- template 配置 --> ??? <!-- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> ??????? <constructor-arg ref="mongo" /> --> ??????? <!-- 數(shù)據(jù)庫名稱 --> ??????? <!-- <constructor-arg value="docdetection" /> --> ??????? <!-- 權(quán)限? --> ??????? <!-- <constructor-arg ref="userCredentials" /> ??? </bean> --> </beans> |
?
其中mongodb可以有自己單獨(dú)的配置文件,其中mongodb.properties的配置如下,注意下面的mongo.host和mongo.hostport根據(jù)情況選擇自己需要的
mongo.host=127.0.0.1 #端口號 mongo.port=27017 #mongoDB連接配置 #mongo.hostport=127.0.0.1:27017 mongo.connectionsPerHost=8 mongo.threadsAllowedToBlockForConnectionMultiplier=4 #連接超時時間 mongo.connectTimeout=1000 #等待時間 mongo.maxWaitTime=1500 mongo.autoConnectRetry=true mongo.socketKeepAlive=true #Socket超時時間 mongo.socketTimeout=1500 mongo.slaveOk=true |
?
下面是MongoDB的基礎(chǔ)操作類:
package cn.com.hbny.docdetection.mongodb.base; import java.util.List; ? import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; ? import com.github.pagehelper.PageInfo; ? /** ?* mongodb 基礎(chǔ)操作類 ?* @author 涂作權(quán) 2017年2月26日 ?* @param <T> ?*/ public interface MongodbDao<T> { ??? ???????? /** ???? * \brief 增加對象 ???? * @param t ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日 原始創(chuàng)建接口 ???? */ ??? public void save(T t); ? ??? /** ???? * \brief 插入一個list集合對象? ???? * @param list ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán)? 2017年2月25日?? 原始創(chuàng)建 ???? */ ??? public void insertAll(List<T> list); ? ??? /** ???? * \brief 刪除對象? ???? * @param t ???? * @attention 方法的使用注意事項(xiàng) ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日?? 原始創(chuàng)建 ???? */ ??? public void delete(T t); ? ??? /** ???? * 根據(jù)id 刪除對象 ???? * ???? * @param id ???? */ ??? public void deleteById(String id); ? ??? /** ???? * 根據(jù)條件刪除 ???? */ ??? public void delete(Query query); ? ??? /** ???? * 刪除該collection 的所有的數(shù)據(jù) ???? */ ??? public void deleteAll(); ? ??? /** ???? * \brief 根據(jù)條件更新數(shù)據(jù)信息 ???? * @param query ???? * @param update ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán)? 2017年2月25日? 原始創(chuàng)建 ???? */ ??? public void update(Query query, Update update); ? ??? /** ???? * \brief 查詢所有 ???? * @return ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日? 原始創(chuàng)建 ???? */ ??? public List<T> findAll(); ??? ??? /** ???? * 根據(jù)查詢query 查找list ???? * ???? * @param query ???? * @return ???? */ ??? public List<T> find(Query query); ? ??? /** ???? * 按照字段排序 - 順序? <br/> ???? * @param query??????? 查詢條件? <br/> ???? * @param properties?? 排序字段? <br/> ???? * @return ???? */ ??? public List<T> findWithOrderAsc(Query query, String... properties); ? ??? /** ???? * 按照字段排序 - 逆序 <br/> ???? * @param query??????? 查詢條件? <br/> ???? * @param properties?? 排序字段? <br/> ???? * @return ???? */ ??? public List<T> findWithOrderDesc(Query query, String... properties); ? ??? /** ???? * 根據(jù)查詢query 查找一個對象 ???? * ???? * @param query ???? * @return ???? */ ??? public T findOne(Query query); ? ??? /** ???? * 根據(jù) id 查詢對象 ???? * ???? * @param id ???? * @return ???? */ ??? public T findById(String id); ? ??? /** ???? * 根據(jù)id 和 集合名字查詢對象 ???? * ???? * @param id ???? * @param collectionName ???? * @return ???? */ ??? public T findById(String id, String collectionName); ? ??? /** ???? * 查詢分頁? tips:[不要skip 太多的頁數(shù),如果跳過太多會嚴(yán)重影響效率。最大不要skip 20000頁] ???? * @param page ???? * @param query ???? * @return ???? */ ??? public PageInfo<T> findPage(PageInfo<T> page, Query query); ? ??? /** ???? * \brief 統(tǒng)計條數(shù) ???? * @param query ???? * @return ???? * @attention 方法的使用注意事項(xiàng) ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 修改人 修改時間?? 修改內(nèi)容摘要說明 ???? */ ??? public long count(Query query); ? ??? /** ???? * 獲取需要操作的實(shí)體類class <br/> ???? * 例如: StudentScoreDao extends MongodbDao <b><StudentScore></b> <br/> ???? * 返回的是 <b>StudentScore</b> 的Class ???? * ???? * @return ???? */ ??? public Class<T> getEntityClass(); ? ??? /** ???? * 獲取collection的名字,默認(rèn)是dao范型T的名字 <br/> ???? * 例如: StudentScoreDao extends MongodbDao <b><StudentScore></b> <br/> ???? * 則返回的名字是:<b>StudentScore</b> ???? * ???? * @return ???? */ ??? public String getCollectionName(); } |
?
MongodbDao的實(shí)現(xiàn)類MongodbDaoImpl:
package cn.com.hbny.docdetection.mongodb.base.impl; import java.util.List; ? import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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.github.pagehelper.PageInfo; ? import cn.com.hbny.docdetection.mongodb.base.MongodbDao; import cn.com.hbny.docdetection.utils.ReflectionUtils; ? /** ?* mongodb 基礎(chǔ)操作類 ?* @author chenpengye 2015年12月21日 下午11:33:06 ?* @param <T> ?*/ public class MongodbDaoImpl<T> implements MongodbDao<T> { ? ??? private static final Logger logger = LoggerFactory.getLogger(MongodbDaoImpl.class); ? ??? //private static final int DEFAULT_SKIP = 0; ??? //private static final int DEFAULT_LIMIT = 200; ? ??? @Autowired ??? protected MongoTemplate mongoTemplate; ? ??? /** ???? * \brief 增加對象 ???? * @param t ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日 原始創(chuàng)建接口 ???? */ ??? public void save(T t) { ??????? mongoTemplate.save(t); ??????? logger.debug("save entity: {}", t); ??? } ? ??? /** ???? * \brief 插入一個list集合對象? ???? * @param list ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán)? 2017年2月25日?? 原始創(chuàng)建 ???? */ ??? public void insertAll(List<T> list) { ??????? mongoTemplate.insertAll(list); ??? } ? ??? /** ???? * \brief 刪除對象? ???? * @param t ???? * @attention 方法的使用注意事項(xiàng) ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日?? 原始創(chuàng)建 ???? */ ??? public void delete(T t) { ??????? mongoTemplate.remove(t); ??? } ? ??? /** ???? * 根據(jù)id 刪除對象 ???? * ???? * @param id ???? */ ??? public void deleteById(String id) { ??????? Criteria criteria = Criteria.where("id").is(id); ??????? Query query = new Query(criteria); ??????? mongoTemplate.remove(query, this.getEntityClass()); ??? } ? ??? /** ???? * 根據(jù)條件刪除 ???? */ ??? public void delete(Query query) { ??????? mongoTemplate.remove(query, this.getEntityClass()); ??? } ? ??? /** ???? * 刪除該collection 的所有的數(shù)據(jù) ???? */ ??? public void deleteAll() { ??????? mongoTemplate.dropCollection(this.getEntityClass()); ??? } ? ??? /** ???? * \brief 根據(jù)條件更新數(shù)據(jù)信息 ???? * @param query ???? * @param update ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán)? 2017年2月25日? 原始創(chuàng)建 ???? */ ??? public void update(Query query, Update update) { ??????? mongoTemplate.findAndModify(query, update, this.getEntityClass()); ??? } ? ??? /** ???? * \brief 查詢所有 ???? * @return ???? * @attention ???? * @author toto ???? * @date 2017年2月25日 ???? * @note? begin modify by 涂作權(quán) 2017年2月25日? 原始創(chuàng)建 ???? */ ??? public List<T> findAll(){ ??????? return mongoTemplate.findAll(this.getEntityClass()); ??? } ??? ??? /** ???? * 根據(jù)查詢query 查找list ???? * ???? * @param query ???? * @return ???? */ ??? public List<T> find(Query query) { ??????? return mongoTemplate.find(query, this.getEntityClass()); ??? } ? ??? /** ???? * 按照字段排序 - 順序? <br/> ???? * @param query??????? 查詢條件? <br/> ???? * @param properties?? 排序字段? <br/> ???? * @return ???? */ ??? public List<T> findWithOrderAsc(Query query, String... properties){ ??????? Sort sort = new Sort(Direction.ASC, properties); ??????? query.with(sort); ??????? return mongoTemplate.find(query, this.getEntityClass()); ??? } ? ??? /** ???? * 按照字段排序 - 逆序 <br/> ???? * @param query??????? 查詢條件? <br/> ???? * @param properties?? 排序字段? <br/> ???? * @return ???? */ ??? public List<T> findWithOrderDesc(Query query, String... properties){ ??????? Sort sort = new Sort(Direction.DESC, properties); ??????? query.with(sort); ??????? return mongoTemplate.find(query, this.getEntityClass()); ??? } ? ??? /** ???? * 根據(jù)查詢query 查找一個對象 ???? * ???? * @param query ???? * @return ???? */ ??? public T findOne(Query query) { ??????? return mongoTemplate.findOne(query, this.getEntityClass()); ??? } ? ??? /** ???? * 根據(jù) id 查詢對象 ???? * ???? * @param id ???? * @return ???? */ ??? public T findById(String id) { ??????? return mongoTemplate.findById(id, this.getEntityClass()); ??? } ? ??? /** ???? * 根據(jù)id 和 集合名字查詢對象 ???? * ???? * @param id ???? * @param collectionName ???? * @return ???? */ ??? public T findById(String id, String collectionName) { ??????? return mongoTemplate.findById(id, this.getEntityClass(), collectionName); ??? } ? ??? /** ???? * 查詢分頁? tips:[不要skip 太多的頁數(shù),如果跳過太多會嚴(yán)重影響效率。最大不要skip 20000頁] ???? * @param page ???? * @param query ???? * @return ???? */ ??? public PageInfo<T> findPage(PageInfo<T> page, Query query) { ??????? long count = this.count(query); ??????? page.setTotal(count); ??????? int pageNumber = page.getPageNum(); ??????? int pageSize = page.getPageSize(); ??????? query.skip((pageNumber - 1) * pageSize).limit(pageSize); ?? ?????List<T> list = this.find(query); ??????? page.setList(list); ??????? return page; ??? } ? ??? public long count(Query query) { ??????? return mongoTemplate.count(query, this.getEntityClass()); ??? } ? ??? /** ???? * 獲取需要操作的實(shí)體類class <br/> ???? * 例如: StudentScoreDao extends MongodbDao <b><StudentScore></b> <br/> ???? * 返回的是 <b>StudentScore</b> 的Class ???? * ???? * @return ???? */ ??? public Class<T> getEntityClass() { ??????? return ReflectionUtils.getSuperClassGenricType(getClass()); ??? } ? ??? /** ???? * 獲取collection的名字,默認(rèn)是dao范型T的名字 <br/> ???? * 例如: StudentScoreDao extends MongodbDao <b><StudentScore></b> <br/> ???? * 則返回的名字是:<b>StudentScore</b> ???? * ???? * @return ???? */ ??? public String getCollectionName() { ??????? return getEntityClass().getSimpleName(); ??? } ? } |
下面編寫要存的文檔對象StudentScore.java
package cn.com.hbny.docdetection.mongodb.beans; ? import java.io.Serializable; import java.util.List; ? import org.springframework.data.mongodb.core.mapping.Document; ? /** ?* @brief StudentScore.java 分?jǐn)?shù)測試 ?* @attention 使用注意事項(xiàng) ?* @author toto ?* @date 2017年2月25日 ?* @note begin modify by 修改人 修改時間? 修改內(nèi)容摘要說明 ?*/ @Document(collection = "studentScores") public class StudentScore implements Serializable { ? ???????? private static final long serialVersionUID = 8743196073520676022L; ? ???????? private String id; ??? public String getId() { ??????? return id; ??? } ??? public void setId(String id) { ??????? this.id = id; ??? } ???????? ???????? /** ???????? ?* 學(xué)生姓名 ???????? ?*/ ???????? private String username; ? ???????? /** ???????? ?* 學(xué)生成績 ???????? ?*/ ???????? private List<Double> scoreList; ? ???????? public String getUsername() { ?????????????????? return username; ???????? } ? ???????? public void setUsername(String username) { ?????????????????? this.username = username; ???????? } ? ???????? public List<Double> getScoreList() { ?????????????????? return scoreList; ???????? } ? ???????? public void setScoreList(List<Double> scoreList) { ?????????????????? this.scoreList = scoreList; ???????? } ???????? ???????? @Override ???????? public String toString() { ?????????????????? return "StudentScore [id=" + id + ", username=" + username + ", scoreList=" + scoreList + "]"; ???????? } ? } |
StudentScoreDao.java的代碼如下:
package cn.com.hbny.docdetection.mongodb.studentscore.dao; ? import cn.com.hbny.docdetection.mongodb.base.MongodbDao; ? public interface StudentScoreDao<StudentScore> extends MongodbDao<StudentScore> { ? } |
StudentScoreDaoImpl.java的代碼如下:
package cn.com.hbny.docdetection.mongodb.studentscore.dao.impl; ? import org.springframework.stereotype.Repository; ? import cn.com.hbny.docdetection.mongodb.base.impl.MongodbDaoImpl; import cn.com.hbny.docdetection.mongodb.beans.StudentScore; import cn.com.hbny.docdetection.mongodb.studentscore.dao.StudentScoreDao; ? /** ?* 繼承MongodbDao<br/> ?* 此類對StudentScore對增刪改查和分頁方法都已經(jīng)有了<br/> ?* @author chenpengye ?* 2016年1月4日 下午10:04:25 ?*/ @Repository public class StudentScoreDaoImpl extends MongodbDaoImpl<StudentScore> ???????? implements StudentScoreDao<StudentScore> { ? } |
?
MongoDBController的代碼結(jié)構(gòu)如下:
package cn.com.hbny.docdetection.mongodb.controller; ? import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; ? import javax.annotation.Resource; ? import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; ? import cn.com.hbny.docdetection.controller.base.BaseController; import cn.com.hbny.docdetection.mongodb.beans.StudentScore; import cn.com.hbny.docdetection.mongodb.studentscore.dao.StudentScoreDao; import cn.com.hbny.docdetection.utils.UUIDGenerator; ? @Controller(value = "mongoDBController") @RequestMapping(value = "/mongodb/mongoDBController", ??? method = {RequestMethod.GET,RequestMethod.POST}) public class MongoDBController extends BaseController{ ???????? ???????? @Resource ???????? private StudentScoreDao<StudentScore> studentScoreDao; ???????? //@Autowired ??? //protected MongoTemplate mongoTemplate; ???????? ???????? @ResponseBody ???????? @RequestMapping(value = "/test") ???????? public Map<String, Object> test() { ?????????????????? Map<String, Object> resultMap = new HashMap<String, Object>(); ?????????????????? try { ??????????????????????????? StudentScore studentScore = new StudentScore(); ??????????????????????????? studentScore.setId(UUIDGenerator.generate()); ??????????????????????????? ??????????????????????????? List<Double> scoreList = new ArrayList<Double>(); ??????????????????????????? scoreList.add(92.0); ??????????????????????????? scoreList.add(55.0); ??????????????????????????? scoreList.add(100.0); ??????????????????????????? scoreList.add(70.0); ??????????????????????????? studentScore.setScoreList(scoreList); ??????????????????????????? ??????????????????????????? studentScore.setUsername("張三"); ? ??????????????????????????? studentScoreDao.save(studentScore); ??????????????????????????? //???????????????????????? List<StudentScore> scores = new ArrayList<StudentScore>(); //???????????????????????? for(int i = 0; i <= 20; i++) { //????????????????????????????????? StudentScore ss = new StudentScore(); //????????????????????????????????? ss.setId(UUIDGenerator.generate()); //????????????????????????????????? //????????????????????????????????? List<Double> scoresList = new ArrayList<Double>(); //????????????????????????????????? scoresList.add(10.0 + i); //????????????????????????????????? scoresList.add(14.0 + i); //????????????????????????????????? scoresList.add(30.0 + i); //????????????????????????????????? scoresList.add(20.0 + i); //????????????????????????????????? ss.setScoreList(scoresList); //????????????????????????????????? //????????????????????????????????? scores.add(ss); //???????????????????????? } //???????????????????????? studentScoreDao.insertAll(scores); ??????????????????????????? ??????????????????????????? studentScoreDao.deleteById("849e1838d18e46989a4fb7cd6c2bac75"); ??????????????????????????? studentScoreDao.deleteById("7567f240c2cc4b15a673c46e27d4c3d4"); ??????????????????????????? studentScoreDao.deleteById("7cd824539640487ca0d09f39b3f403c6"); ??????????????????????????? studentScoreDao.deleteById("7f60cc24d9954c1cb196cc3993ec9654"); ??????????????????????????? studentScoreDao.deleteById("4ebf7d0812294a5bba8053d849f42b18"); ??????????????????????????? ??????????????????????????? List<StudentScore> studentScores = studentScoreDao.findAll(); ??????????????????????????? for (StudentScore ss : studentScores) { ???????????????????????????????????? System.out.println(ss.toString()); ??????????????????????????? } ??????????????????????????? ??????????????????????????? resultMap.put("flag", "success"); ?????????????????? } catch (Exception e) { ??????????????????????????? resultMap.put("flag", "error"); ??????????????????????????? e.printStackTrace(); ?????????????????? } ?????????????????? ?????????????????? return resultMap; ???????? } } |
瀏覽器輸入的地址是:http://127.0.0.1:8080/docdetection/mongodb/mongoDBController/test.action
?
控制臺中輸出的結(jié)果如下:
?
以上是MongoDB的配置和使用的介紹
?
總結(jié)
以上是生活随笔為你收集整理的Spring整合Mongodb,Maven的依赖,Spring配置,MongoDB的公共操作类,使用SpringMVC的Controller进行测试并返回结果的案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 煲仔饭为什么会糊?
- 下一篇: “有心了,谢谢你的海鲜大礼包”怎么回复