Spring+SpringMVC+MyBatis的整合

Spring+SpringMVC+MyBatis的整合

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FwPayGap-1601386537437)(https://i.loli.net/2020/06/10/soLQFY3PCXKz6Hy.png)]

1. 在pom.xml中导入所需依赖

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.5.RELEASE</version>
  </dependency>

  <!-- pagehelper分页插件 -->
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.8</version>
  </dependency>

  <!-- Mybatis整合 Spring的适配包 -->
  <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.2</version>
  </dependency>

  <!-- MBG 逆向工程 -->
  <dependency>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-core</artifactId>
    <version>1.3.7</version>
  </dependency>

  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
  </dependency>

  <!-- 数据库连接池、驱动 -->
  <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.20</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.30</version>
  </dependency>

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

  <!-- 返回json字符串的支持 -->
  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
  <dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.9.3</version>
  </dependency>

  <!-- 上传文件依赖 -->
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
  </dependency>
  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
  </dependency>

  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.30</version>
  </dependency>

</dependencies>

2. springMVC的配置

<?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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- SpringMVC的配置文件,包含网站跳转逻辑的控制、配置  -->

    <!-- 配置扫描器: 只扫描有 @Controller注解的包 -->
    <!-- <context:component-scan base-package="wb.wust.controller"></context:component-scan> -->
    <context:component-scan base-package="ssm.integration" use-default-filters="false">
        <!-- 只扫描控制器 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 配置试图解析器(InternalResourceViewResolver) -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" /><!-- 前缀 -->
        <property name="suffix" value=".html" /><!-- 后缀 -->
    </bean>

    <!-- 要释放的资源 -->
    <mvc:resources mapping="/layui/**" location="/WEB-INF/layui/"/>

    <!-- ***两个标准配置*** -->
    <!-- (过滤静态资源)将 SpringMVC不能处理的请求交给 tomcat -->
    <mvc:default-servlet-handler/>
    <!-- 能支持 SpringMVC更高级的一些功能,如 JSR303校验,快捷 ajax请求等...映射动态请求  -->
    <mvc:annotation-driven />

    <!--
      配置 CommonsMultipartResolver,用于实现文件上传 ,将其加入 springIoC 容器
      springIoC 容器在初始化时,会自动寻找一个 id="multipartResolver" 的 bean 并将其加到 IOC 容器
   -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 上传单个文件的最大值,单位是 byte。这里设置为 5M -->
        <property name="maxUploadSize" value="5242880" />
        <!-- 最大上传内存大小 -->
        <property name="maxInMemorySize" value="4096" />
    </bean>
    
</beans>

3. db.properties的配置

jdbc.driver=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/数据库名称
jdbc.username=root
jdbc.password=
jdbc.maxActive=500
jdbc.maxIdle=1000

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

   <!-- Spring 的配置文件,这里主要配置和业务逻辑有关的 -->

   <context:component-scan base-package="ssm.integration">
      <!-- 在 spring中,不扫控制器 -->
      <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>

   <!-- 加载 db.properties 配置文件 -->
   <context:property-placeholder location="classpath:db.properties" />

   <!-- (数据源)配置数据信息(替代 mybatis 的配置文件 conf.xml) -->
   <bean id="pooledDataSource" class="com.alibaba.druid.pool.DruidDataSource">
      <property name="driverClassName" value="${jdbc.driver}"/>
      <property name="url" value="${jdbc.jdbcUrl}"/>
      <property name="username" value="${jdbc.username}"/>
      <property name="password" value="${jdbc.password}"/>
   </bean>

   <!-- Spring 整合 Mybatis 的配置 -->
   <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean" >
      <!-- 指定 mybatis全局配置文件的位置 -->
      <property name="configLocation" value="classpath:mybatis-config.xml" />
      <!-- 数据源 -->
      <property name="dataSource" ref="pooledDataSource"/>
      <!-- 指定 mybatis,mapper配置文件的位置 -->
      <property name="mapperLocations" value="classpath:mapper/*.xml"/>
   </bean>

   <!-- 配置扫描器,将 mybatis接口的实现加入到 IoC容器中 -->
   <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
      <property name="basePackage" value="ssm.integration.dao" />
      <!--<property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"/>-->
   </bean>

   <!-- 配置一个可以执行批量的 sqlSession -->
   <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
      <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
      <constructor-arg name="executorType" value="BATCH"/>
   </bean>

   <!-- 事务管理器 -->
   <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="pooledDataSource" />
   </bean>
   <!--开启声明式注解管理事务-->
   <tx:annotation-driven transaction-manager="transactionManager"/>

</beans>

5. mybatis-config.xml的配置

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 设置全局变量 -->
    <settings>
        <!-- 开启驼峰命名规则 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- 打印 sql语句 -->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <!-- 类型别名,在 mapper使用时可直接使用类名 -->
        <package name="ssm.integration.pojo"/>
    </typeAliases>

    <!-- 注册分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 分页参数合理化 -->
            <property name="reasonable" value="true"/>
        </plugin>
    </plugins>
</configuration>

6. web.xml的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5" 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">
  <display-name>ssm-crud</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

  <!-- 1、启动 spring 的容器 -->
  <!-- needed for ContextLoaderListener -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- Bootstraps the root web application context before servlet initialization-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!-- 2、SpringMVC的前端控制器,拦截所有请求 -->
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- Map all requests to the DispatcherServlet for handling -->
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern> <!-- /:代表一切请求 -->
  </servlet-mapping>

  <!-- 3、字符编码过滤器,一定要放在所有过滤器之前 -->
  <filter>
    <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

</web-app>

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

  <context id="DB2Tables" targetRuntime="MyBatis3">
  
   <!-- 去掉注释 -->
   <commentGenerator>
     <property name="suppressAllComments" value="true" />
   </commentGenerator>
  
   <!-- 配置数据库连接 -->
    <jdbcConnection 
       driverClass="com.mysql.jdbc.Driver"
        connectionURL="jdbc:mysql://localhost:3306/数据库名"
        userId="root"
        password="">
    </jdbcConnection>

    <javaTypeResolver >
      <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

   <!-- 指定 javaBean生成的位置 -->
    <javaModelGenerator 
       targetPackage="ssm.integration.pojo"
       targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
      <property name="trimStrings" value="true" />
    </javaModelGenerator>

   <!-- 指定 sql映射文件生成的位置 -->
    <sqlMapGenerator 
       targetPackage="mapper"  
       targetProject=".\src\main\resources">
      <property name="enableSubPackages" value="true" />
    </sqlMapGenerator>

   <!-- 指定 dao接口生成的位置,mapper接口 -->
    <javaClientGenerator type="XMLMAPPER" 
       targetPackage="ssm.integration.dao"
       targetProject=".\src\main\java">
      <property name="enableSubPackages" value="true" />
    </javaClientGenerator>

   <!-- table指定每张表的生成策略 -->
    <table tableName="数据库表名" domainObjectName="实体类名" />
  </context>
</generatorConfiguration>

8. mbg.xml配置的使用,在test包下新建一个MBGTest类

package ssm.integration.test;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;

public class MBGTest {

   public static void main(String[] args) throws Exception {
      List<String> warnings = new ArrayList<>();
      boolean overwrite = true;
      File configFile = new File("mbg.xml");
      ConfigurationParser cp = new ConfigurationParser(warnings);
      Configuration config = cp.parseConfiguration(configFile);
      DefaultShellCallback callback = new DefaultShellCallback(overwrite);
      MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
      myBatisGenerator.generate(null);
   }
}
已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页