Spring整合Mongodb,Maven的依赖,Spring配置,MongoDB的公共操作类,使用SpringMVC的Controller进行测试并返回结果的案例

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 MongoDB,通用型 2核4GB
简介: 在和Spring和MongoDB进行整合的时候需要如下三个jar,分别是:spring-data-commons spring-data-mongodb mongo-java-driver 下面讲解Spring和MongoDB2.x进行整合的Spring配置(下面案例以下面的方式进行说明:)Maven的Pom文件的配置如下:<dependency> &lt

在和Spring和MongoDB进行整合的时候需要如下三个jar,分别是:

spring-data-commons

spring-data-mongodb

mongo-java-driver

下面讲解Spring和MongoDB2.x进行整合的Spring配置(下面案例以下面的方式进行说明:)

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所在的项目位置处执行如下命令:

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>

如果用到分页相关的插件,可以按照如下方式配置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的配置处进行如下配置:

<?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" />

  

   <!-- 定时器驱动 -->

   <task:annotation-driven/>

 

   <!-- 引入jdbc配置文件 -->

   <context:property-placeholder location="classpath:jdbc.properties,classpath:mongodb.properties" />

 

   <!--

   以下用于配置多数据源

   配置parentDataSource的父bean,再配置多个数据源继承这个bean,driverClassName

   urlusernamepassword等数据源连接参数进行各自的重写、例如mysqlDataSource

   DataSource bean中要注入所要切换的数据、并且设置默认的数据源

    -->

   <!--<bean id="parentDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"></bean>

    创建MySQL对应的jdbc数据源

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

   -->

  

   <!-- 数据源 org.apache.commons.dbcp.BasicDataSource com.alibaba.druid.pool.DruidDataSource -->

   <bean id="parentDataSource" class="com.alibaba.druid.pool.DruidDataSource">

       <!-- 初始化连接大小 -->

       <property name="initialSize" value="8" />

       <!-- 连接池最大使用连接数量 -->

       <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" />

      

       <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->

       <property name="timeBetweenEvictionRunsMillis" value="60000" />

       <!-- 配置一个连接池中最小生存的时间,单位是毫秒 -->

       <property name="minEvictableIdleTimeMillis" value="25200000" />

      

       <!-- 打开removeAbandoned功能 -->

       <property name="removeAbandoned" value="true" />

       <!-- 1800秒,也就是30分钟 -->

       <property name="removeAbandonedTimeout" value="1800" />

       <!-- 关闭abanded连接时输出错误日志 -->

       <property name="logAbandoned" value="true" />

       <!-- 监控数据库 -->

       <property name="filters" value="mergeStat" />

   </bean>

  

   <!-- 创建MySQL对应的jdbc数据源 -->

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

 

   <!--创建jdbc数据源 -->

   <!-- <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是自己定义的数据源-->

   <!-- 注意下面的cn.com.hbny.docdetection.mapper.base.impl.DataSources是自己定义的数据源-->

   <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监控spring jdbc -->

   <bean id="druid-stat-interceptor"

        class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor">

    </bean>

     

   <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->

   <bean id="transactionManager"

      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

      <property name="dataSource" ref="dataSource" />

   </bean>

   <!-- 声明式事务 -->

   <tx:annotation-driven transaction-manager="transactionManager"

       proxy-target-class="true"/>

 

   <!-- 创建SqlSessionFactory,同时指定数据源 -->

   <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对应的配置 -->

    <!-- 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对象,对应的是mongodb官方jar包中的Mongoreplica-set设置集群副本的ip地址和端口 -->

    <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}">

       <!-- 一些连接属性的设置 -->

       <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实例,dbnamemongodb的数据库名,没有的话会自动创建 -->

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

   

    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->

    <mongo:mapping-converter base-package="cn.com.hbny.docdetection.mongodb.beans" />

    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 -->

    <mongo:repositories base-package="cn.com.hbny.docdetection" />

    <!--  *******************************************方式2:结束***************************** -->

   

    <!-- 方式3配置 -->

    <!--

          对应的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" /> -->

        <!-- 数据库名称 -->

        <!-- <constructor-arg value="docdetection" /> -->

        <!-- 权限  -->

        <!-- <constructor-arg ref="userCredentials" />

    </bean> -->

</beans>

 

其中mongodb可以有自己单独的配置文件,其中mongodb.properties的配置如下,注意下面的mongo.host和mongo.hostport根据情况选择自己需要的

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的基础操作类:

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 基础操作类

 * @author 涂作权 2017年2月26日

 * @param <T>

 */

public interface MongodbDao<T> {

   

         /**

     * \brief 增加对象

     * @param t

     * @attention

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权 2017年2月25日 原始创建接口

     */

    public void save(T t);

 

    /**

     * \brief 插入一个list集合对象 

     * @param list

     * @attention

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权  2017年2月25日   原始创建

     */

    public void insertAll(List<T> list);

 

    /**

     * \brief 删除对象 

     * @param t

     * @attention 方法的使用注意事项

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权 2017年2月25日   原始创建

     */

    public void delete(T t);

 

    /**

     * 根据id 删除对象

     *

     * @param id

     */

    public void deleteById(String id);

 

    /**

     * 根据条件删除

     */

    public void delete(Query query);

 

    /**

     * 删除该collection 的所有的数据

     */

    public void deleteAll();

 

    /**

     * \brief 根据条件更新数据信息

     * @param query

     * @param update

     * @attention

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权  2017年2月25日  原始创建

     */

    public void update(Query query, Update update);

 

    /**

     * \brief 查询所有

     * @return

     * @attention

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权 2017年2月25日  原始创建

     */

    public List<T> findAll();

   

    /**

     * 根据查询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);

 

    /**

     * 根据查询query 查找一个对象

     *

     * @param query

     * @return

     */

    public T findOne(Query query);

 

    /**

     * 根据 id 查询对象

     *

     * @param id

     * @return

     */

    public T findById(String id);

 

    /**

     * 根据id 和 集合名字查询对象

     *

     * @param id

     * @param collectionName

     * @return

     */

    public T findById(String id, String collectionName);

 

    /**

     * 查询分页  tips:[不要skip 太多的页数,如果跳过太多会严重影响效率。最大不要skip 20000页]

     * @param page

     * @param query

     * @return

     */

    public PageInfo<T> findPage(PageInfo<T> page, Query query);

 

    /**

     * \brief 统计条数

     * @param query

     * @return

     * @attention 方法的使用注意事项

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 修改人 修改时间   修改内容摘要说明

     */

    public long count(Query query);

 

    /**

     * 获取需要操作的实体类class <br/>

     * 例如: StudentScoreDao extends MongodbDao <b>&lt;StudentScore&gt;</b> <br/>

     * 返回的是 <b>StudentScore</b> 的Class

     *

     * @return

     */

    public Class<T> getEntityClass();

 

    /**

     * 获取collection的名字,默认是dao范型T的名字 <br/>

     * 例如: StudentScoreDao extends MongodbDao <b>&lt;StudentScore&gt;</b> <br/>

     * 则返回的名字是:<b>StudentScore</b>

     *

     * @return

     */

    public String getCollectionName();

}

 

MongodbDao的实现类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 基础操作类

 * @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 涂作权 2017年2月25日 原始创建接口

     */

    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 涂作权  2017年2月25日   原始创建

     */

    public void insertAll(List<T> list) {

        mongoTemplate.insertAll(list);

    }

 

    /**

     * \brief 删除对象 

     * @param t

     * @attention 方法的使用注意事项

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权 2017年2月25日   原始创建

     */

    public void delete(T t) {

        mongoTemplate.remove(t);

    }

 

    /**

     * 根据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());

    }

 

    /**

     * 根据条件删除

     */

    public void delete(Query query) {

        mongoTemplate.remove(query, this.getEntityClass());

    }

 

    /**

     * 删除该collection 的所有的数据

     */

    public void deleteAll() {

        mongoTemplate.dropCollection(this.getEntityClass());

    }

 

    /**

     * \brief 根据条件更新数据信息

     * @param query

     * @param update

     * @attention

     * @author toto

     * @date 2017年2月25日

     * @note  begin modify by 涂作权  2017年2月25日  原始创建

     */

    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 涂作权 2017年2月25日  原始创建

     */

    public List<T> findAll(){

        return mongoTemplate.findAll(this.getEntityClass());

    }

   

    /**

     * 根据查询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());

    }

 

    /**

     * 根据查询query 查找一个对象

     *

     * @param query

     * @return

     */

    public T findOne(Query query) {

        return mongoTemplate.findOne(query, this.getEntityClass());

    }

 

    /**

     * 根据 id 查询对象

     *

     * @param id

     * @return

     */

    public T findById(String id) {

        return mongoTemplate.findById(id, this.getEntityClass());

    }

 

    /**

     * 根据id 和 集合名字查询对象

     *

     * @param id

     * @param collectionName

     * @return

     */

    public T findById(String id, String collectionName) {

        return mongoTemplate.findById(id, this.getEntityClass(), collectionName);

    }

 

    /**

     * 查询分页  tips:[不要skip 太多的页数,如果跳过太多会严重影响效率。最大不要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());

    }

 

    /**

     * 获取需要操作的实体类class <br/>

     * 例如: StudentScoreDao extends MongodbDao <b>&lt;StudentScore&gt;</b> <br/>

     * 返回的是 <b>StudentScore</b> 的Class

     *

     * @return

     */

    public Class<T> getEntityClass() {

        return ReflectionUtils.getSuperClassGenricType(getClass());

    }

 

    /**

     * 获取collection的名字,默认是dao范型T的名字 <br/>

     * 例如: StudentScoreDao extends MongodbDao <b>&lt;StudentScore&gt;</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 分数测试

 * @attention 使用注意事项

 * @author toto

 * @date 2017年2月25日

 * @note begin modify by 修改人 修改时间  修改内容摘要说明

 */

@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;

    }

        

         /**

          * 学生姓名

          */

         private String username;

 

         /**

          * 学生成绩

          */

         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对增删改查和分页方法都已经有了<br/>

 * @author chenpengye

 * 2016年1月4日 下午10:04:25

 */

@Repository

public class StudentScoreDaoImpl extends MongodbDaoImpl<StudentScore>

         implements StudentScoreDao<StudentScore> {

 

}

 

MongoDBController的代码结构如下:

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

 

控制台中输出的结果如下:

 

以上是MongoDB的配置和使用的介绍

 

相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
1月前
|
Java Spring
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
使用JDBCTemplate实现与Spring结合,方法公用 ——测试(EmpDaoImplTest)
9 0
|
3月前
|
消息中间件 Java 测试技术
Spring Cloud Alibaba环境问题之测试环境失败如何解决
Spring Cloud Alibaba提供了一套在Spring Cloud框架基础上构建的微服务解决方案,旨在简化分布式系统的开发和管理;本合集将探讨Spring Cloud Alibaba在实际应用中的部署和使用技巧,以及该框架常见问题的诊断方法和解决步骤。
|
4月前
|
Java Maven Spring
【Spring】Maven项目的创建
【Spring】Maven项目的创建
|
4月前
|
存储 Java 测试技术
《Spring 测试指南》:JPA、MockMvc 和 @SpringBootTest 详解
Spring 提供了一组测试工具,可以轻松地测试 Spring 应用程序的各个组件,包括控制器、服务、存储库和其他组件。它具有丰富的测试注释、实用程序类和其他功能,以帮助进行单元测试、集成测试等。
61 0
|
1月前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
26 0
|
3月前
|
Java 数据库 数据安全/隐私保护
基于SSM框架实现管科类考研自我管理系统(分前后台spring+springmvc+mybatis+maven+jsp+jquery)
基于SSM框架实现管科类考研自我管理系统(分前后台spring+springmvc+mybatis+maven+jsp+jquery)
|
1月前
|
前端开发 Java 网络安全
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
10 0
|
1月前
|
前端开发 Java
Springmvc入门案例(1)
Springmvc入门案例(1)
7 0
|
1月前
|
Java Spring
使用spring实现邮件的发送(含测试,源码,注释)
使用spring实现邮件的发送(含测试,源码,注释)
7 0
|
1月前
|
前端开发 Java 数据库连接
基于 Spring MVC + MyBits + Maven
基于 Spring MVC + MyBits + Maven
290 0

推荐镜像

更多