前阵子公司要求做的一个小项目,然后尝试着用mongodb非关系型数据库去做,发现还挺有意思的。

为了少点儿戴绿帽子我决定还是先分享出来。

在做的过程中,SSM集成框架和Mongodb融合在一起再加个用户名校验对Spring版本Mongodb的版本有点儿严格要求,在这里我这边用Mongodb3.6版本来做本实例,ide我用的是intellij idea ,关于如何新建项目、如何配置tomcat、Mongodb如何搭建等问题我就不balabala说了 ,出门右拐搜索。

一:新建项目后先导入maven包、我直接从原项目里拷过去,够用了

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>SSMMongoDemo</groupId>
  <artifactId>SSMMongoDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>SSMMongoDemo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <spring.version>5.0.7.RELEASE</spring.version>
    <aspectj.version>1.8.9</aspectj.version>
    <cglib.version>3.2.4</cglib.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <!--<version>3.8.1</version>-->
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>commons-lang</groupId>
      <artifactId>commons-lang</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.31</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.2.7</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.2.2</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.30</version>
    </dependency>
    <!-- mongoDB支持jar -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-mongodb</artifactId>
      <version>1.8.0.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
      <scope>provided</scope>
    </dependency>

    <!--JSP标准标签库(JSTL)-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>1.6.1</version>
    </dependency>

    <!--区别slf4j与log4j-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.7</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-nop</artifactId>
      <version>1.7.5</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    <dependency>
      <groupId>org.testng</groupId>
      <artifactId>testng</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>qiniu-java-sdk</artifactId>
      <version>7.2.6</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.3.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.6.2</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>com.qiniu</groupId>
      <artifactId>happy-dns-java</artifactId>
      <version>0.1.4</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.6.4</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>SSMMongoDemo</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.7.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.20.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

这里包括了Mysql等各种包。

二、在根目录新建Java和resources两个文件夹,分别右键设置为java root 和 resources root

此时的文件架构是这样的。

mybatisPlus 使用mongodb mybatis操作mongodb_Spring-data-mongodb

然后在java里新建模型、控制、和服务层文件夹、不需要dao啥的。

mybatisPlus 使用mongodb mybatis操作mongodb_SpringMVC_02

三、在resources里新建各种配置文件、如下

config.properties

#mongoDB连接配置

#IP地址
mongo.host= 127.0.0.1
#端口
mongo.port=28023
#数据库名
mongo.defaultDbName=mydemo
mongo.connectionsPerHost=10
mongo.threadsAllowedToBlockForConnectionMultiplier=5
mongo.minConnectionsPerHost=5
#连接超时时间
mongo.connectTimeout=100000
#等待时间
mongo.maxWaitTime=1200000
#Socket超时时间
mongo.socketTimeout=0
mongo.socketKeepAlive=true

mongo.description=joyven test mongodb database
mongo.maxConnectionIdleTime=15000
mongo.maxConnectionLifeTime=0
#mongo slave
mongo.heartbeatSocketTimeout=10000
mongo.heartbeatConnectTimeout=15000
mongo.minHeartbeatFrequency=50
mongo.heartbeatFrequency=100

帐号密码不在这里配置。

log4j.properties

log4j.rootLogger = DEBUG,stdout,file
log4j.logger.org.apache.ibatis=warn
log4j.logger.java.sql=warn
log4j.logger.org.springframework=warn
# Druid
log4j.logger.druid.sql=DEBUG
log4j.logger.druid.sql.DataSource=warn
log4j.logger.druid.sql.Connection=warn
log4j.logger.druid.sql.Statement=DEBUG
log4j.logger.druid.sql.ResultSet=warn
log4j.logger.cn.wdq=DEBUG,wdq


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.Threshold=DEBUG
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss}[ %p ]%m%n

logging.properties

handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler  

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE  
org.apache.juli.FileHandler.directory = ${catalina.base}/logs  
org.apache.juli.FileHandler.prefix = error-debug.  

java.util.logging.ConsoleHandler.level = FINE  
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为10MB 10*1024*1024(妈个鸡好像不管用) -->
        <property name="maxUploadSize">
            <value>10485760</value>
        </property>
    </bean>
    <!--只在springmvc容器中配置controller的扫描-->
    <context:component-scan base-package="com.azimiao.controller" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <mvc:annotation-driven/>

    <!-- 将在Controller返回的ModelAndView,加上目录前缀/WEB-INF/views/, 文件名称后缀.jsp -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <!--<beans:property name="prefix" value="/WEB-INF/views/"/>-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

mongodb-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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-2.5.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/data/mongo
        http://www.springframework.org/schema/data/mongo/spring-mongo.xsd ">



    <!--加载mongodb的属性配置文件-->
    <context:property-placeholder location="classpath:config.properties"/>

    <!--credentials="development:zy@deve^lop*ment#.iox*&nm324dsfk@admin"-->
    <mongo:mongo-client id="mongoClient"  host="${mongo.host}" port="${mongo.port}" credentials="development:zy@deve^lop*ment#.iox*&nm324dsfk@admin">
        <mongo:client-options
                connections-per-host="${mongo.connectionsPerHost}"
                min-connections-per-host="${mongo.minConnectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                connect-timeout="${mongo.connectTimeout}"
                max-wait-time="${mongo.maxWaitTime}"
                socket-keep-alive="${mongo.socketKeepAlive}"
                socket-timeout="${mongo.socketTimeout}"
                description="${mongo.description}"
                max-connection-idle-time="${mongo.maxConnectionIdleTime}"
                max-connection-life-time="${mongo.maxConnectionLifeTime}"
                heartbeat-socket-timeout="${mongo.heartbeatSocketTimeout}"
                heartbeat-connect-timeout="${mongo.heartbeatConnectTimeout}"
                min-heartbeat-frequency="${mongo.minHeartbeatFrequency}"
                heartbeat-frequency="${mongo.heartbeatFrequency}"

        />
    </mongo:mongo-client>

    <mongo:db-factory id="mongoDbFactory"
                      mongo-ref="mongoClient"/>


    <mongo:mapping-converter id="converter"
                             db-factory-ref="mongoDbFactory" />
    <!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
    <mongo:db-factory dbname="azimiao" mongo-ref="mongoClient"/>


    <mongo:template id="mongoTemplate" db-factory-ref="mongoDbFactory" write-concern="NORMAL"/>

    <!-- 映射转换器,扫描back-package目录下的文件,根据注释,把它们作为mongodb的一个collection的映射 -->
    <mongo:mapping-converter base-package="com.azimiao.model"/>

    <!-- mongodb bean的仓库目录,会自动扫描扩展了MongoRepository接口的接口进行注入 (暂时没啥用)-->
    <!--<mongo:repositories base-package="com.fwb.repository"/>-->

    <!-- MongoDB GridFS Template 文件上传-->
    <bean id="gridFsTemplate" class="org.springframework.data.mongodb.gridfs.GridFsTemplate">
        <constructor-arg ref="mongoDbFactory" />
        <constructor-arg ref="converter" />
    </bean>

</beans>

用户名和密码验证在credentials这里、格式是  用户名:密码@默认数据库

spring-context.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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd">


    <context:component-scan base-package="com.azimiao">
        <!-- 排除不扫描的,controller放在子容器springmvc的配置文件中 -->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--导入mongodb的配置文件-->
    <import resource="mongodb-context.xml"/>


</beans>

最后一步是修改web.xml

web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app
        version="3.0"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <!--指定欢迎页面-->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!--1、在web.xml配置监听器ContextLoaderListener-->
  <!--ContextLoaderListener的作用(一句话):初始化BeanFactory,并将BeanFactory设置到application中。-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-context.xml</param-value>
  </context-param>

  <!--Spring log4j Config loader-->


  <context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>

  <!--使用Spring MVC,配置DispatcherServlet是第一步。DispatcherServlet是一个Servlet,
  所以可以配置多个DispatcherServlet-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc-servlet.xml</param-value>
    </init-param>
    <!--是启动顺序,让这个Servlet随Servletp容器一起启动。-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 在Spring框架中是如何解决从页面传来的字符串的编码问题的呢?
  下面我们来看看Spring框架给我们提供过滤器CharacterEncodingFilter
   这个过滤器就是针对于每次浏览器请求进行过滤的,然后再其之上添加了父类没有的功能即处理字符编码。
    其中encoding用来设置编码格式,forceEncoding用来设置是否理会 request.getCharacterEncoding()方法,设置为true则强制覆盖之前的编码格式。-->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.html</url-pattern>
  </servlet-mapping>



  <session-config><!--会话超时配置,单位分钟-->
    <session-timeout>360</session-timeout>
  </session-config>
</web-app>

接着就配置tomcat、这儿用的是tomcat8.5、裸奔一下看看有没有报错啥的。

mybatisPlus 使用mongodb mybatis操作mongodb_Spring-data-mongodb_03

mybatisPlus 使用mongodb mybatis操作mongodb_Spring_04

OK。没问题了。接下来做一个好玩的demo。