前提:如何要整合SpringMVC 與Mybatis,首先要會配置SpringMVC
第一部分:配置SpringMVC
第一步:導入jar包

第二步:構建一個請求
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/say.do">say</a>
</body>
</html>
第三步:配置核心控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xml="http://www.w3.org/XML/1998/namespace" 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_3_0.xsd ">
<!-- 配置核心控制器攔截所有的請求 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定配置文件的路徑 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
第四步:創建一個業務控制器
@Controller //組件注解 public class HelloController { @RequestMapping(value="/say") public String say(){ System.out.println("HelloWorld!"); return "/hello.jsp"; } }
第五步:創建Spring配置文件
<?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-4.3.xsd"> <!-- 配置組件掃描器 --> <context:component-scan base-package="cn.px.controller"></context:component-scan> </beans>
第六步:創建一個返回頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> 你好世界 </body> </html>
問題:為什么需要配置核心控制器。
答:因為我們只能在網站的入口(web.xml)攔截了所有的請求,我們才能做到請求與方法的一一對應!!
問題:為什么需要配置<init-param>
答:因為我們希望指定自定義的配置文件路徑。如果使用框架默認的路徑可以不配置
問題:為什么需要配置<context:component-scan>
答:因為我們是通過組件注解(@Controller)的方式,將類的對象加載到容器里面。所以必須要配置
第二部分:配置Mybatis
第一步:導入jar包

第二步:創建配置文件
--注意:Mybatis的配置文件使用DTD規范文件的。所以需要通過DTD規則文件生成。
問題:為什么配置文件使用xml
答:就是因為大部分的IDE(開發工具)對xml有提示功能的。
問題:為什么xml會有提示功能呢?
答:因為xml的標簽有約束文件來約束標簽與標簽之間的關系。開發工具通過約束文件來提供對應的標簽。
問題:xml的約束文件有哪些呢?
答:DTD 以及 schema
問題:為什么有一些xml文件Eclipse直接支持提示了呢?
答:因為這個xml的文件的規則文件已經內置在Eclipse開發工具里面了。
問題:Mybatis的DTD,Eclipse工具默認是沒有的,怎么辦?
答:那么我們需要在Eclipse里面配置它!!!
這也告訴了我們,任何框架,只要使用XML配置,它就必須要提供DTD或者Schema。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
<environments default="sms">
<!-- 任何配置文件,的參數都可以在框架代碼里面找到!! -->
<!-- 大部分的框架,對配置文件的解釋的所在類的分包的包名,configuration以及縮寫、builder以及縮寫 -->
<environment id="sms">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<!-- property 對應的就是set方法-->
<property name="driver" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/sms"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>
第三步:創建幫助類MybatisUtils
public class MybatisUtils { public static final SqlSessionFactory SSF=MybatisUtils.getSSF(); private static final ThreadLocal<SqlSession> THREAD_LOCAL=new ThreadLocal<>(); /** * 獲得會話工廠 * @return */ private static SqlSessionFactory getSSF() { try { Reader reader = Resources.getResourceAsReader("mybatis-config.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); return builder.build(reader); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 獲得會話 * @return */ public static SqlSession getSession(){ if(THREAD_LOCAL.get()==null){ SqlSession session = SSF.openSession(); THREAD_LOCAL.set(session); } return THREAD_LOCAL.get(); } /** * 關閉會話 */ public static void close(){ if(THREAD_LOCAL.get()!=null){ SqlSession session = THREAD_LOCAL.get(); session.close(); THREAD_LOCAL.remove(); } } public static void main(String[] args) { System.out.println(MybatisUtils.getSession()); } }
第四步:創建映射接口
public interface StudentMapper { /** * 插入學生 * @param student * @return */ int insert(Student student); }
第五步:創建並加載映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="cn.px.mapper.StudentMapper">
<insert id="insert">
INSERT INTO tb_student (stu_name, stu_age, stu_password) VALUES (#{stuName}, #{stuAge}, #{stuPassword})
</insert>
</mapper>
<mappers>
<mapper resource="cn/px/mapper/xml/StudentMapper.xml"/>
</mappers>
第六步:測試插入數據
public class StudentMapperTest { @Test public void insert(){ //第一步:獲得操作對象 SqlSession session = MybatisUtils.getSession(); StudentMapper studentMapper = session.getMapper(StudentMapper.class); Student student=new Student(); student.setStuName("張三"); int count = studentMapper.insert(student); System.out.println(count); session.commit(); MybatisUtils.close(); }
實體類
public class Student { private String stuId; private String stuName; private String stuAge; private String stuPassword; public String getStuId() { return stuId; } public void setStuId(String stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuAge() { return stuAge; } public void setStuAge(String stuAge) { this.stuAge = stuAge; } public String getStuPassword() { return stuPassword; } public void setStuPassword(String stuPassword) { this.stuPassword = stuPassword; } }
第三部分:整合SpringMVC與Mybatis
問題:為什么需要SpringMVC整合Mybatis?
答:因為我們希望Mybatis可以使用Spring框架里面的事務代理機制。
問題:Spring框架的事務代理依賴什么東西?
答:Spring JDBC里面的數據源!!
所以所謂的SpringMVC整合Mybatis就是,就是讓Mybatis拋棄自己實現的數據源,在使用Spring提供的數據源。
那么整合步驟:
第一步:導入jar包

第二步:配置文件
<?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" 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-4.3.xsd"> <!-- 1.配置數據源 --> <bean name="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close"> <!-- 四要素 --> <property name="driverClassName" value="org.gjt.mm.mysql.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/sms" /> <property name="username" value="root" /> <property name="password" value="123456" /> </bean> <!-- 2.配置會話工廠 --> <!-- 默認情況下:mybatis是不支持spring的數據源的 --> <!-- 問題:那么我們如何可以讓mybatis支持spring的數據源呢? --> <!-- 答:需要一個整合包 mybatis-spirng.jar SqlSessionFactoryBean:作用就是讓Mybatis可以通過Spring的數據源創建會話工廠的 --> <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定數據源 --> <property name="dataSource" ref="dataSource"></property> <!-- 加載映射文件的路徑 --> <property name="mapperLocations" value="classpath:cn/px/mapper/xml/*Mapper.xml"></property> </bean> <!-- 3.配置掃描器,將映射接口的動態對象創建,並且注入到spring容器里面 --> <!-- 默認情況下:spring是不支持通過接口創建對象!!而Mybatis就是通過接口創建對象的 問題:Spring必須要實現類創建可以注入到容器,而Mybatis就是使用接口創建動態對象的。不能兼容Spring的要求。怎么辦呢? 答:整合包提供了一個映射接口掃描器,用於通過映射接口創建了對象,並且可以創建的對象注入到容器里面 -根據表述掃描器必要要的兩個條件 1.需要會話工廠 2.必須要指定映射接口的路徑 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> <property name="basePackage" value="cn.px.mapper"></property> <!-- 指定掃描注解 --> <property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"></property> </bean> <!-- 4.配置事務代理,編程式事務 --> <!-- 注意:Mybatis是的spring jdbc的事務代理 --> <!-- 創建事務代理對象 --> <bean name="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 指定數據源 --> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 啟動事務代理 --> <tx:annotation-driven/> </beans>
