springMvc+spring+mybatis整合

下载地址:https://download.csdn.net/download/qq_18430613/10638679

1.先来看看整个项目的结构

2.好了废话不说了 先来建一个webapp 骨架的web项目,建好后如下结构(修改web.xml 文件为2.5,2.5之前的版本需要修改相关配置所以尽量使用2.5版本,详见如下图

 

3.添加依赖

1) 在添加依赖之前先修改pom.xml 文件的编译码,以及相关插件(这里主要使用通用mapper)

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
</properties>
<build>
  <finalName>SSM</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>
  <plugins>
    <plugin>
      <groupId>org.mybatis.generator</groupId>
      <artifactId>mybatis-generator-maven-plugin</artifactId>
      <version>1.3.2</version>
      <configuration>
        <!-- generator 工具配置文件的位置 -->
        <configurationFile>src/main/resources/generatorConfiguration.xml</configurationFile>
        <!--允许移动生成的文件 -->
        <verbose>true</verbose>
        <!--允许覆盖生成的文件 -->
        <overwrite>true</overwrite>
      </configuration>
      <dependencies>
        <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.6</version>
        </dependency>
        <dependency>
          <groupId>org.mybatis.generator</groupId>
          <artifactId>mybatis-generator-core</artifactId>
          <version>1.3.2</version>
        </dependency>
        <dependency>
          <groupId>tk.mybatis</groupId>
          <artifactId>mapper</artifactId>
          <version>3.3.9</version>
        </dependency>
      </dependencies>
    </plugin>
  </plugins>
</build>

2)添加pom依赖,以下所有主要配置都有相关注释

<!--ssm 整合-->
<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <!--整合spring-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.0.6.RELEASE</version><!--4.3.14.RELEASE-->
  </dependency>

  <!--使用aop 管理配置事物 -->
  <dependency>
    <groupId>aopalliance</groupId>
    <artifactId>aopalliance</artifactId>
    <version>1.0</version>
  </dependency>

  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.8.10</version>
  </dependency>

  <!--jdbc 事物管理依赖-->
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.14.RELEASE</version>
  </dependency>

  <!--数据库&& 数据库连接池-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
  </dependency>

  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
  </dependency>

  <!--mybatis 整合到spring 的依赖-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.1</version>
  </dependency>

  <!--mybatis 配置-->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
  </dependency>

  <dependency>
    <groupId>tk.mybatis</groupId>
    <artifactId>mapper</artifactId>
    <version>3.3.9</version>
  </dependency>

  <!--web-->
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
  </dependency>

  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
  </dependency>

  <!--json-->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.5</version>
  </dependency>
</dependencies>

4.添加通用mapper资源到相关配置文件

#mybatisGeneratorinit.properties 相关配置
#Mybatis Generator configuration
#dao类和实体类的根的位置
project =src/main/java
#mapper文件的位置
resources=src/main/resources/mybatis
#根据数据库中的表生成对应的pojo类、dao、mapper
jdbc_driver =com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/mysql
jdbc_user=root
jdbc_password=123456

mapper.plugin = tk.mybatis.mapper.generator.MapperPlugin
# 指定生成的Mapper文件集成的接口
mapper.Mapper = com.common.base.mapper.BaseMapper

generatorConfiguration.xml 相关配置

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="mybatisGeneratorinit.properties"/>
    <!-- 一个数据库一个context -->
    <!--defaultModelType="flat" 大数据字段,不分表 -->
    <context id="MysqlTables" targetRuntime="MyBatis3Simple" defaultModelType="flat">
        <!-- 自动识别数据库关键字,默认false,如果设置为true,根据SqlReservedWords中定义的关键字列表;
        一般保留默认值,遇到数据库关键字(Java关键字),使用columnOverride覆盖 -->
        <property name="autoDelimitKeywords" value="true" />
        <!-- 生成的Java文件的编码 -->
        <property name="javaFileEncoding" value="utf-8" />
        <!-- beginningDelimiter和endingDelimiter:指明数据库的用于标记数据库对象名的符号,比如ORACLE就是双引号,MYSQL默认是`反引号; -->
        <property name="beginningDelimiter" value="`" />
        <property name="endingDelimiter" value="`" />
 
        <!-- 格式化java代码 -->
        <property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
        <!-- 格式化XML代码 -->
        <property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin" />
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin" />
        <!-- 通用mapper插件 -->
        <plugin type="${mapper.plugin}">
          <property name="mappers" value="${mapper.Mapper}"/>
        </plugin>
 
        <!-- 注释 -->
        <commentGenerator >
            <property name="suppressAllComments" value="false"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true" /> <!-- 是否生成注释代时间戳-->
        </commentGenerator>
 
        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc_driver}" connectionURL="${jdbc_url}" userId="${jdbc_user}" password="${jdbc_password}" />
        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
 
        <!-- 生成实体类地址 -->
        <javaModelGenerator targetPackage="com.gerry.domain" targetProject="${project}" >
            <property name="enableSubPackages" value="false"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <!-- 生成mapxml文件 -->
        <sqlMapGenerator targetPackage="mappers" targetProject="${resources}" >
            <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>
        <!-- 生成mapxml对应client,也就是接口mapper -->
        <javaClientGenerator targetPackage="com.gerry.mapper" targetProject="${project}" type="XMLMAPPER" >
            <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- table可以有多个,每个数据库中的表都可以写一个table,tableName表示要匹配的数据库表,也可以在tableName属性中通过使用%通配符来匹配所有数据库表,只有匹配的表才会自动生成文件 -->
        <table tableName="tb_user" domainObjectName="UserInfo">
            <!-- 数据库表主键 -->
            <generatedKey column="userId" sqlStatement="Mysql" identity="true" />
        </table>

        <table tableName="t_book" domainObjectName="BookInfo">
            <!-- 数据库表主键 -->
            <generatedKey column="bookId" sqlStatement="Mysql" identity="true" />
        </table>
    </context>
</generatorConfiguration>

至此,通用mapper已经全部配置完毕,下面需要通过执行插件来生成 实体对象,mapper.xml 文件以及接口文件(执行的时候请确认,生成的包路径是否添加,如果没有添加需要手动添加,比如:com.common.base.mapper.BaseMapper 看看是否有baseMapper 文件,还有mybatis.mappers 相关文件是否创建

5.生成相关实体,mapper 和接口文件 生成后整个目录格式如下:

6.整合springmvc+spring + mybaits 配置文件

1)  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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--用于管理spring容器相关配置文件-->
    <import resource="classpath:spring/spring-datasource.xml" />
    <import resource="classpath:spring/spring-mybatis.xml" />
    <import resource="classpath:spring/spring-service.xml" />
    <import resource="classpath:spring/spring-tx.xml" />
</beans>

2. spring-datasource.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"
       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">
   <!--加载资源文件-->
    <context:property-placeholder location="classpath:datasource/datasource.properties" />
    <!--配置数据库源以及数据库连接池-->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" >
        <property name="driverClassName" value="${jdbc.driver_class}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="initialSize" value="${initialSize}" />
        <property name="minIdle" value="${minIdle}" />
        <property name="maxWait" value="${maxWait}" />
        <property name="testOnBorrow" value="${testOnBorrow}" />
    </bean>
</beans>

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

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" >
        <property name="dataSource" ref="dataSource" />
        <!--把mybatis所有mapper映射配置文件整合到sqlSessionFactory对象中-->
        <property name="mapperLocations" value="classpath:mybatis/mappers/*Mapper.xml" />
    </bean>

    <bean id="mapperScanner" class="tk.mybatis.spring.mapper.MapperScannerConfigurer" >
        <property name="basePackage" value="com.*.mapper" />
    </bean>
</beans>

4.spring-service.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"
       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">
    <!--扫描所有service交给spring容器管理-->
    <context:component-scan base-package="com.*.service" />
</beans>

5.spring-tx.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:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="modify*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="SUPPORTS"/>
            <tx:method name="find*" propagation="SUPPORTS"/>
            <tx:method name="list*" propagation="SUPPORTS"/>
            <tx:method name="*" propagation="SUPPORTS" read-only="true" rollback-for="com.common.base.exception.BaseBusinessException" />
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="pcut" expression="execution(* com.*.service.impl.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pcut" />
    </aop:config>
</beans>

6.spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:component-scan base-package="com.*.controller" />
    <mvc:annotation-driven />

    <bean name="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
        <property name="order" value="0"/>
    </bean>

    <!--配置拦截器-->
    <!--<mvc:interceptors>
            <bean class="com.demo.interceptor.LoginInterceptor" />
            <mvc:interceptor>
                    <mvc:mapping path="/user/**"/>
                    &lt;!&ndash;排除不需要拦截的路径&ndash;&gt;
                    <mvc:exclude-mapping path="/user/login" />
                    <bean class="com.demo.interceptor.DataInterceptor" />
            </mvc:interceptor>
    </mvc:interceptors>-->

    <!--文件上传配置-->
    <!--<bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
        <property name="maxUploadSize" value="-1" />
        <property name="maxUploadSizePerFile" value="2048000" />
        <property name="maxInMemorySize" value="2048000" />
    </bean>-->

</beans>

7.web.xml 添加SpringMVC的前端控制器,当前web容器实例化的时候也实例spring容器

<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd"
           version="2.5">

    <!--配置编码过滤器filter-->
    <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>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--配置SpringMVC的前端控制器-->
    <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:spring/spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!--当前web容器实例化的时候也实例spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-context.xml</param-value>
    </context-param>
</web-app>

 

OK 到此 为止 可以自己写个 jsp 和 controller 来测试下了 。。

 

 

 

版权声明:本文为qq_18430613原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_18430613/article/details/82257477