一、前提
1、查看不同 MyBatis 版本整合 Spring 时使用的适配包
http://www.mybatis.org/spring/
2、下载整合适配包
https://github.com/mybatis/spring/releases
3、官方整合示例 jpetstore
https://github.com/mybatis/jpetstore-6
二、搭建环境
1、使用 Maven 创建一个 web 项目;
2、导入需要添加的依赖
(1)导入 SSM 需要使用的 jar 包(Spring,SpringMVC,MyBatis);
(2)导入整合适配包
(3)导入其他技术的一些支持包,如连接池,数据库驱动,日志等……
(4)导入第三方支持的包:log4j,pageHelper,AspectJ,jackson,jstl
3、依赖文件
<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>
<spring-version>4.0.0.RELEASE</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- ehcache 相关包-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.8</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.2</version>
</dependency>
<!-- mybatis-spring 相关包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- spring 相关包-->
<!-- IOC-->
<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-expression</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!-- 数据库相关 -->
<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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- springMVC 相关-->
<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>
<!--JSTL-->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-spec</artifactId>
<version>1.2.1</version>
</dependency>
<!--日志相关-->
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.2.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<!-- jetty 插件 -->
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.25</version>
<configuration>
<!-- 热部署,每10秒扫描一次 -->
<scanIntervalSeconds>10</scanIntervalSeconds>
<!-- 可指定当前项目的站点名 -->
<contextPath>/ssm</contextPath>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<!-- 设置启动的端口号 -->
<port>9090</port>
</connector>
</connectors>
</configuration>
</plugin>
<!-- Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8080</port> <!-- 设置启动的端口号 默认8080 -->
<path>/ssm</path> <!-- 项目的站点名,即对外访问路径 -->
<uriEncoding>UTF-8</uriEncoding> <!-- 字符集编码 默认:ISO-8859-1 -->
<server>tomcat7</server> <!-- 服务器名称 -->
</configuration>
</plugin>
</plugins>
</build>
三、SpringMVC 配置
1、配置 web.xml
(1)字符编码过滤器
(2)REST 风格的过滤器:HiddenHTTPMethodFilter
(3)核心控制器(前端控制器):DispatcherServlet
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>SSM项目整合</display-name>
<!--Spring 配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--SpringMVC 的配置-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2、springMVC 配置文件
在 WEB-INF 目录创建 spring-servlet.xml进行 springMVC 的配置
(1)扫描控制层组件
(2)视图解析器
(3)默认的Servlet:Default Servlet
(4)MVC 驱动
(5)可选:MultipartResolver、拦截器
配置文件 spring-servlet:
<?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">
<!--SpringMVC 只是控制网站跳转逻辑 -->
<!--只扫描控制器-->
<context:component-scan base-package="com.njf.mybatis" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!-- 视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
配置文件的名称为web.xml中DispatcherServlet的name加上 -servlet 拼接而成。
3、整合 SpringMVC 和 Spring
在web.xml 中
(1)实例化 Spring 容器的监听器:ContextLoaderListener
(2)配置 context-param,指定spring 配置文件的位置
四、Spring 配置
在 resources 目录下创建 application.xml 配置文件:
(1)扫描组件(排除控制层)
(2)事务管理器
(3)配置连接池
(4)配置数据源
配置文件:
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-sprin="http://mybatis.org/schema/mybatis-spring"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!-- Spring 希望管理所有的业务逻辑组件,等 -->
<context:component-scan base-package="com.njf.mybatis" use-default-filters="true">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入数据库的配置文件-->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!-- Spring 控制业务逻辑,数据源、事务控制,aop -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring 事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启基于注解的事务-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
</beans>
数据库连接信息 db-config.xml:
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=root
五、引入 MyBatis
1、核心(全局)配置文件 mybatis-config.xml
2、mapper 接口和 mapper 映射文件
六、Spring 整合 MyBatis
在 application.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:tx="http://www.springframework.org/schema/tx"
xmlns:mybatis-sprin="http://mybatis.org/schema/mybatis-spring"
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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">
<!-- Spring 希望管理所有的业务逻辑组件,等 -->
<context:component-scan base-package="com.njf.mybatis" use-default-filters="true">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入数据库的配置文件-->
<context:property-placeholder location="classpath:dbconfig.properties" />
<!-- Spring 控制业务逻辑,数据源、事务控制,aop -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="driverClass" value="${jdbc.driver}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring 事务管理器-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--开启基于注解的事务-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
<!--
整合 mybatis
目的:
1、spring 管理所有组件,mapper 的实现类
service ===》Dao @Autowired 自动注入的 mapper
2、spring 用来管理事务,声明式事务
-->
<!--
创建出 SqlSessionFactory 对象
-->
<bean id="sessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.njf.mybatis.bean"/>
<property name="typeAliases">
<array>
<value>com.njf.mybatis.bean.Employee</value>
<value>com.njf.mybatis.bean.Department</value>
</array>
</property>
<!-- configLocation 指定全局配置文件的位置-->
<property name="configLocation" value="classpath:mybatis-config.xml" />
<!-- 指定mapper 文件的位置 -->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
</bean>
<!--
扫描所有的mapper接口的实现,让这些 mapper 能够自动注入
base-package:指定mapper接口的包名
-->
<!--<mybatis-sprin:scan base-package="com.njf.mybatis.dao"></mybatis-sprin:scan>-->
<!--老版格式-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.njf.mybatis.dao"/>
</bean>
</beans>
<?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="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="lazyLoadingEnabled" value="true"/>
<!--
aggressiveLazyLoading:侵入延迟加载,当使用任一属性,所有的属性都会加载;禁用的话,只有用到该属性才会加载,即按需加载
-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
<databaseIdProvider type="DB_VENDOR">
<!-- 为不同的数据库厂商起别名 -->
<property name="MySQL" value="mysql"/>
<property name="SQL Server" value="sqlserver"/>
<property name="DB2" value="db2"/>
<property name="Oracle" value="oracle" />
</databaseIdProvider>
</configuration>
部分源码:
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean, ApplicationListener<ApplicationEvent> {
private static final Log LOGGER = LogFactory.getLog(SqlSessionFactoryBean.class);
private Resource configLocation;
private Configuration configuration;
private Resource[] mapperLocations;
private DataSource dataSource;
private TransactionFactory transactionFactory;
private Properties configurationProperties;
private SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
private SqlSessionFactory sqlSessionFactory;
private String environment = SqlSessionFactoryBean.class.getSimpleName();
private boolean failFast;
private Interceptor[] plugins;
private TypeHandler<?>[] typeHandlers;
private String typeHandlersPackage;
private Class<?>[] typeAliases;
private String typeAliasesPackage;
private Class<?> typeAliasesSuperType;
private DatabaseIdProvider databaseIdProvider;
private Class<? extends VFS> vfs;
private Cache cache;
private ObjectFactory objectFactory;
private ObjectWrapperFactory objectWrapperFactory;
}
七、最终测试
1、dao 层
public interface EmployeeMapper {
public Employee getEmpById(Integer id);
}
映射文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.njf.mybatis.dao.EmployeeMapper">
<!--
public Employee getEmpById(Integer id);
-->
<select id="getEmpById" resultType="Employee">
select * from tbl_employee
where id = #{id}
</select>
</mapper>
2、service 层
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
@Override
public Employee getEmpById(Integer id) {
return employeeMapper.getEmpById(id);
}
}
3、controller 层
@Controller
public class EmployeeController {
@Autowired
private EmployeeService employeeService;
@RequestMapping("emps")
public String getEmployee(Map<String, Object> map) {
Employee emp = employeeService.getEmpById(1);
map.put("emp", emp);
return "list";
}
}
4、视图层
index.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>SSM测试</title>
</head>
<body>
<a href="emps">查询员工</a>
<a href="dept">查询部门</a>
</body>
</html>
list.jsp
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>
员工信息
</title>
</head>
<body>
员工信息:
${emp}
${emp.id}
${emp.lastName}
<br>
请求域
${requestScope.emp}
<%=request.getAttribute("emp") %>
<hr>
部门信息
${dept}
<%=request.getAttribute("dept") %>
</body>
</html>