Fork me on GitHub

Spring__SpringMVC__Mybatis整合

Springmvc是controller层的,mybatis是dao和mapper层的,而spring类似粘合剂,springmvc与mybatis之间是不能直接整合的,而是通过springmvc和spring之间,mybatis与spring之间整合的。

Spring容器和SpringMVC容器的关系

Spring容器是一个父容器,SpringMVC容器是一个子容器,它继承自Spring容器。因此,在SpringMVC容器中,可以访问到Spring容器中定义的Bean,而在Spring容器中,无法访问SpringMVC容器中定义的Bean。在Web开发中,Controller全部在SpringMVC中扫描,除了Controller之外的Bean,全部在Spring容器中扫描(Service、Dao),按这种方式扫描,扫描完完成后,Controller可以访问到Service。

为什么不全部都在Spring中扫描

因为处理器映射器只会去SpringMVC中查找到Controller,如果没有,就找不到,不会去Spring中找,这就决定了,Controller必须在SpringMVC中扫描。Controller在SpringMVC中扫描,视图解析器等在SpringMVC容器中配置。

为什么不全部在SpringMVC中扫描

在SSM整合或者Spring+SpringMVC+JdbcTemplate中,可以全部在SpringMVC中扫描,但是,在SSH整合中,这种方式不允许。Spring中扫描Service、Dao已经其他组件,事务定义、数据源定义都在Spring容器中配置。

demo的结构

加入依赖

<dependencies>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-aop</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-aspects</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-beans</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-context-support</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-core</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-expression</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-orm</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-tx</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-web</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.springframework</groupId>
  		<artifactId>spring-webmvc</artifactId>
  		<version>4.3.10.RELEASE</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis-spring</artifactId>
  		<version>1.3.2</version>
  	</dependency>
  	<dependency>
  		<groupId>org.mybatis</groupId>
  		<artifactId>mybatis</artifactId>
  		<version>3.4.6</version>
  	</dependency>
  	<dependency>
  		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.41</version>
  	</dependency>
  	<dependency>
  		<groupId>com.mchange</groupId>
  		<artifactId>c3p0</artifactId>
  		<version>0.9.5.2</version>
  	</dependency>
  	<dependency>
  		<groupId>log4j</groupId>
  		<artifactId>log4j</artifactId>
  		<version>1.2.17</version>
  	</dependency>
  	<dependency>
  		<groupId>org.slf4j</groupId>
  		<artifactId>slf4j-log4j12</artifactId>
  		<version>1.7.25</version>
  	</dependency>
  </dependencies>

spring

applicationContext-dao.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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- 引入外部文件 -->
	<context:property-placeholder
		location="classpath:resource/db.properties" />

	<!-- 数据源,数据连接池 -->
	<bean id="dataSource"
		class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${driver}"></property>
		<property name="jdbcUrl" value="${url}"></property>
		<property name="user" value="${names}"></property>
		<property name="password" value="${password}"></property>
	</bean>

	<!-- 配置sqlsessionFactory -->
	<bean id="sqlSessionFactory"
		class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="configLocation"
			value="classpath:mybatis/mybatis-cfg.xml"></property>
		<property name="dataSource" ref="dataSource"></property>
		<!-- 添加别名设置 -->
		<property name="typeAliasesPackage" value="com.zsl.pojo"/>
	</bean>
	
	<!-- 配置扫描包,加载mapper代理对象 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.zsl.mapper"></property>
	</bean>
	
</beans>

applicationContext-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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- 扫描service -->
	<context:component-scan
		base-package="com.zsl.service" />
	<!-- 开启自动注入注解,上面开启了扫描,所以不需要自动注入 -->
	<!-- <context:annotation-config /> -->


</beans>

事务相关
applicationContext-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:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.3.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<!-- 配置Spring的事务管理 -->
    <!-- 事务管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

springMVC

springMVC.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:aop="http://www.springframework.org/schema/aop"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd">


<!-- <context:property-placeholder
		location="classpath:*.properties" /> -->
	<!-- 开启扫描 -->	
	<context:component-scan
		base-package="com.zsl.controller" />

<!—-自动注入中央控制器,处理器映射器,处理器适配器 -->
	<mvc:annotation-driven />

	  <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 设置前后缀 -->
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

	<!-- 防止资源文件被spring MVC拦截 -->
	<mvc:resources mapping="/img/**" location="/img/"
		cache-period="31556926" />
	<mvc:resources mapping="/js/**" location="/js/"
		cache-period="31556926" />
	<mvc:resources mapping="/css/**" location="/css/"
		cache-period="31556926" />
</beans>

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">

	<!-- 加载spring容器 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/applicationContext-*.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- springmvc的前端控制器 -->
	<servlet>
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/springMVC.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<!-- 解决post乱码 -->
	<filter>
		<filter-name>encoding</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>encoding</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

</web-app>

mybatis

全局配置文件mybatis-cfg.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="lazyLoadingEnabled" value="true"/>
  	<setting name="aggressiveLazyLoading" value="false"/>
  </settings> 
</configuration>

资源文件

使用逆向工程生成的pojo和映射文件

service层

package com.zsl.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zsl.mapper.EmpMapper;
import com.zsl.pojo.Emp;
import com.zsl.pojo.EmpExample;
import com.zsl.pojo.EmpExample.Criteria;
import com.zsl.service.IEmpService;
@Service
public class EmpServiceImpl implements IEmpService {
	@Autowired
	private EmpMapper empMapper;
	
	@Override
	public List<Emp> query() {
		EmpExample example = new EmpExample();
		List<Emp> list = empMapper.selectByExample(example);
		return list;
	}

	@Override
	public List<Emp> queryByName(String ename) {
		// TODO Auto-generated method stub
		EmpExample example = new EmpExample();
		Criteria criteria = example.createCriteria();
		criteria.andEnameLike(ename);
		List<Emp> list = empMapper.selectByExample(example);
		return list;
	}

	@Override
	public Integer addEmp(Emp emp) {
		// TODO Auto-generated method stub
		int insertSelective = empMapper.insertSelective(emp);
		return insertSelective;
	}

	@Override
	public Integer updateEmp(Emp emp) {
		// TODO Auto-generated method stub
		int updateByPrimaryKey = empMapper.updateByPrimaryKey(emp);
		return updateByPrimaryKey;
	}

	@Override
	public Integer deleteEmp(Integer empno) {
		// TODO Auto-generated method stub
		int deleteByPrimaryKey = empMapper.deleteByPrimaryKey(empno);
		return deleteByPrimaryKey;
	}

}

controller层

package com.zsl.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zsl.pojo.Emp;
import com.zsl.service.IEmpService;

@Controller
public class TestAction {
	@Autowired
	private IEmpService empService;
	
	@RequestMapping("/query")
	@ResponseBody
	public void query() {
		// TODO Auto-generated method stub
		List<Emp> list = empService.query();
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
	
	@RequestMapping("/queryByName")
	@ResponseBody
	public void queryByName(String ename) {
		// TODO Auto-generated method stub
		List<Emp> list = empService.queryByName(ename);
		for (Emp emp : list) {
			System.out.println(emp);
		}
	}
	
	@RequestMapping("/addEmp")
	@ResponseBody
	public void addEmp(Emp emp) {
		// TODO Auto-generated method stub
		Integer addEmp = empService.addEmp(emp);
		System.out.println("新增了:"+addEmp);
	}
	
	@RequestMapping("/updateEmp")
	@ResponseBody
	public void updateEmp(Emp emp){
		Integer updateEmp = empService.updateEmp(emp);
		System.out.println("修改了:"+updateEmp);
	}
	
	@RequestMapping("/deleteEmp")
	@ResponseBody
	public void deleteEmp(Integer empno) {
		// TODO Auto-generated method stub
		Integer deleteEmp = empService.deleteEmp(empno);
		System.out.println("删除了:"+deleteEmp);
	}
	
}

1.springmvc在action层,配置过滤器,拦截器,视图解析器,(中央控制器,处理器映射器,处理器适配器等,开启了<mvc:annotation-driven />,就不用我们手动去配置了),防止静态资源文件被拦截等web端需要的可以在springmvc进行配置。

mvc:annotation-driven 注解的作用

Spring 3.0.x中使用了mvc:annotation-driven后,默认会帮我们注册默认处理请求,参数和返回值的类,其中最主要的两个类:DefaultAnnotationHandlerMapping 和 AnnotationMethodHandlerAdapter ,分别为HandlerMapping的实现类和HandlerAdapter的实现类,从3.1.x版本开始对应实现类改为了RequestMappingHandlerMapping和RequestMappingHandlerAdapter。

HandlerMapping的实现类的作用
实现类RequestMappingHandlerMapping,它会处理@RequestMapping 注解,并将其注册到请求映射表中。

HandlerAdapter的实现类的作用
实现类RequestMappingHandlerAdapter,则是处理请求的适配器,确定调用哪个类的哪个方法,并且构造方法参数,返回值。

当配置了mvc:annotation-driven/后,Spring就知道了我们启用注解驱动。然后Spring通过context:component-scan/标签的配置,会自动为我们将扫描到的@Component,@Controller,@Service,@Repository等注解标记的组件注册到工厂中,来处理我们的请求。

2.mybatis中有可以设置开启延迟加载和二级缓存以及分页插件等
为什么不在mybatis中配置sqlsessionfactory了?
因为sqlsessionfactory需要获取xml等配置文件去解析后得到sqlsession对象的,这里mybatis没有解析xml等配置文件,spring去解析了xml配置文件,而且要把sqlsessionfactory对象交给springIOC容器去管理,所以在spring中配置sqlsessionfactory。

3.spring中配置数据源,sqlsessionfactory对象,开启扫描service包以及mapper包,事务,开启自动注入(<context:annotation-config />)

posted @ 2019-07-13 15:55  偷偷学习被我发现  阅读(527)  评论(0编辑  收藏  举报