springmvc+spring+mybatis整合 idea版

最近公司要开发新项目记录下过程:给大家一个参考,优美不优美大家自己评论

创建maven项目

在这里插入图片描述
当然jdk 根据自己的需要选择版本,我现在一直用的1.8
在这里插入图片描述
groupid 一般公司域名倒着写 artifactID 项目名称
也可以groupid 公司域名加项目名称用.分隔,artifactid用-分隔
在这里插入图片描述
maven选择
新建项目完成

整合顺序

在这里插入图片描述
1.spring为核心 我们先添加spring的支持
2.spring 再整合mybatis
3.spring 整合springmvc

mave 依赖

pom 添加依赖

<?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>com.dhcc.ecs</groupId>
  <artifactId>com-dhcc-ecs</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

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

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>

    <java.version>1.8</java.version>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <!--lib setting-->
    <spring.version>4.3.3.RELEASE</spring.version>
    <jackson.version>2.6.3</jackson.version>


  </properties>

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

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.39</version>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.1</version>
    </dependency>

    <!-- DAO框架:mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.1</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <!-- servlet 相关依赖-->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.6.7</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>

    <!--spring依赖-->
    <!--1)核心依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</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>
    <!--2)spring DAO-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--3)spring web-->
    <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>
    </dependency>
    <!--4)spring test-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>



  </dependencies>

  <build>
    <finalName>com-dhcc-ecs</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.1.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.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</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>

文件结构先大致添加好

在这里插入图片描述
在这里插入图片描述

spring 支持

配置文件 applicationContext

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx-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/context
       http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://cxf.apache.org/jaxws 	
       http://cxf.apache.org/schemas/jaxws.xsd
     ">

	<!-- 加载系统模块配置文件begin -->
	<context:component-scan base-package="com.hrp.**.serviceImpl"
		use-default-filters="false">
		<context:include-filter type="annotation"
			expression="org.springframework.stereotype.Service" />
	</context:component-scan>
	<!-- 加载系统模块配置文件end -->

测试类

 @Test
    public void  test1(){

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        DemoService demoService= (DemoService) applicationContext.getBean("demoService");
        demoService.findAll();
    }

SpringMvc 支持

web.xml 配置

<!--spring mvc 支持 前端控制器-->
  <servlet>
    <servlet-name>hrp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:hrp.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>hrp</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!--解决乱码问题-->
  <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>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

springmvc 配置我这里名字为hrp.xml
1.开启扫码功能 只扫描controller层
2.jsp视图解析器 我这里用的html不是jsp freemarker模板
3.过滤静态资源文件
4.开启扫码

<!-- 过滤静态资源文件访问 -->
	<mvc:resources location="/lib/" mapping="/lib/**" />

	<mvc:default-servlet-handler />

	
	
	<!--登陆 用户 等注解探测器,表示不需要为每个访问路径配置控制类 -->
	<!--开启扫描-->
	<context:component-scan base-package="com.hrp.**.controller" use-default-filters="false">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	<!--开启注解功能-->
	<mvc:annotation-driven />

	<!--&lt;!&ndash; 拦截器设置,处理session超时,自动跳转到登录页面 &ndash;&gt;-->
	<!--<mvc:interceptors>-->
		<!--<bean class="com.base.InterceptorController" />-->
	<!--</mvc:interceptors>-->


	<!-- jsp视图解析器 -->
	<!--bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/" />
		<property name="suffix" value=".html" />
	</bean-->

	<!-- 设置freeMarker的配置文件路径 -->
    <bean id="freemarkerConfiguration"
          class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <!--注释掉的下方代码是指引freemarker的基本信息的配置位置,因为我已经将配置信息移到了applicationContext文件下,所以这里就没必要存在了,不注释也不会有问题的 -->
        <!--<property name="location" value="classpath:/WEB-INF/config/freemarker.properties" />-->
    </bean>

spring 和 springmvc 整合

我们现在想想有一个问题就是spring配置文件没有被加载,但是所以我们在tomcat启动的时候需要加载spring的配置文件
servletcontext 域对象
服务器启动的创建servletcontext 域对象 服务器关闭的时候才销毁
其中有一类监听监听servletcontext 域对象的创建和销毁
因此我们使用监听器去加重spring的配置文件

这一段我们自己好好理解下
spring-web jar提供相关的监听器

web.xml 中添加

<!--默认值加载web-inf 的applicationContext.xml 所以我们需要初始化文件位置-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

此时controller就可以注入service了

@Controller
@RequestMapping("/demo")
public class DemoController {

    **@Resource
    DemoService demoService;**

    @RequestMapping("/demo")
    public  void demotest(){
        demoService.findAll();
        System.out.println("controller======" );
    }
}

添加mybatis 支持

sqlMapConfig.xml mybatis 主配置文件
和mapper.hrp下面的 mapper配置文件

<?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="lazyLoadingEnabled" value="true"/><!-- 使用延迟加载 -->
        <setting name="aggressiveLazyLoading" value="false"/><!-- 按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其他的懒对象属性) -->
        <setting name="cacheEnabled" value="true"/><!-- 开启二级缓存,默认是false -->
        <setting name="callSettersOnNulls" value="true"/><!--解决,查询返回结果含null没有对应字段值问题-->
        <setting name="mapUnderscoreToCamelCase" value="true"/> <!--开启驼峰命名,比如 mysql 中的字段  User_Code  对应Java bean中的userCode -->
        <!--<setting name="logImpl" value="STDOUT_LOGGING" />-->
        <!--有效值-->
        <!--SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING-->
        <setting name="logImpl" value="LOG4J" />
    </settings>
    <typeAliases>
        <!--单个类命名-->
        <typeAlias type="com.hrp.sys.entity.SysUser" alias="sysUser"/>
        <!--也可以使用注解@Alias-->
        <!--批量将一个包下的所有类都起别名-->
        <package name="com.hrp.sys.entity"></package>
    </typeAliases>
    
    <environments default="">
        <environment id="">
            <!--<transactionManager type=""></transactionManager>-->
            <!--<dataSource type=""></dataSource>-->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://ip:3306/databsename?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;autoReconnect=true&amp;failOverReadOnly=false&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="****"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/hrp/demo/DemoMapper.xml"></mapper>

    </mappers>
</configuration>

<!-- 
cacheEnabled  对在此配置文件下的所有cache 进行全局性开/关设置。true | false 。默认:true
lazyLoadingEnabled 全局性设置懒加载。如果设为‘false’,则所有相关联的都会被初始化加载。true | false。默认:true
aggressiveLazyLoading 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载。true | false。默认:true
multipleResultSetsEnabled 允许和不允许单条语句返回多个数据集(取决于驱动需求)true | false。默认:true
useColumnLabel 使用列标签代替列名称。不同的驱动器有不同的作法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。true | false。默认:true
useGeneratedKeys 允许JDBC 生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。true | false。默认:false
autoMappingBehavior 指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。NONE,PARTIAL,FULL。默认:PARTIAL
defaultExecutorType 配置和设定执行器,SIMPLE 执行器执行其它语句。REUSE 执行器可能重复使用prepared statements 语句,BATCH执行器可以重复执行语句和批量更新。SIMPLE,REUSE,BATCH。默认:SIMPLE,
defaultStatementTimeout 设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时。正整数。默认:Not Set
 -->

spirng mybatis 整合

spirng配置xml文件中
1.配置连接池
2. 配置sqlsessionfactory工厂
3. 配置maperr文件

spring 事务添加

1.配置事务管理器
2. 事务通知
3. 配置aop增强

<!-- spring 声明式的事务 -->
	<aop:aspectj-autoproxy />

	<aop:config>
		<aop:pointcut id="appService"
			expression="execution(* com.hrp.**..service..*Service*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="appService" />
	</aop:config>
	<!-- PROPAGATION_REQUIRED 支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。<br> PROPAGATION_SUPPORTS支持当前事务,如果当前没有事务,就以非事务方式执行。
		PROPAGATION_MANDATORY 支持当前事务,如果当前没有事务,就抛出异常。 PROPAGATION_REQUIRES_NEW新建事务,如果当前存在事务,把当前事务挂起。
		PROPAGATION_NOT_SUPPORTED 以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。 PROPAGATION_NEVER以非事务方式执行,如果当前存在事务,则抛出异常。
		PROPAGATION_NESTED 如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED类似的操作。 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<!-- 添加数据 纳入事物拦截的方法前缀 -->
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="init*" propagation="REQUIRED" />
		

			<tx:method name="*" propagation="SUPPORTS" />


		</tx:attributes>
	</tx:advice>

	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章