Spring+SpringMVC+Mybatis—三个框架(SSM)整合

文章目录

      • 1、整合注意事项
      • 2、整合思路、步骤
        • (1)搭建环境
        • (2)Spring + Springmvc
        • (3)MyBatis
        • (4)Spring + MyBatis
        • (5)测试: REST CRUD
      • 3、整合的配置
        • 3.1 web.xml
        • 3.2 Spring 配置
        • 3.3 SpringMVC配置
        • 3.4 MyBatis配置
        • 3.5 Spring整合Mybatis配置
      • 4、整合测试
      • 5、整合案例(详细代码)
        • 5.1 环境准备
          • (1)创建动态web工程并导入jar包
          • (2)db.properties
          • (3)log4j.xml
        • 5.2 配置web.xml文件
        • 5.3 Javabean
        • 5.4 mapper层(dao层)
        • 5.5 配置SQL映射文件
        • 5.6 service层
        • 5.7 controller层
        • 5.8 配置applicationContext.xml文件
        • 5.9 配置spring-mvc.xml文件
        • 5.10 配置mybatis的主配置文件
        • 5.11 创建index.jsp页面
        • 5.12 创建list.jsp页面
        • 5.13 效果

1、整合注意事项

(1)查看不同MyBatis版本整合Spring时使用的适配包;

(2)下载整合适配包

https://github.com/mybatis/spring/releases

(3)官方整合示例,jpetstore

https://github.com/mybatis/jpetstore-6

2、整合思路、步骤

(1)搭建环境

​ 创建一个动态的WEB工程

​ 导入SSM需要使用的jar包

​ 导入整合适配包

​ 导入其他技术的一些支持包 连接池 数据库驱动 日志…

(2)Spring + Springmvc

​ 在web.xml中配置: Springmvc的前端控制器 实例化Spring容器的监听器 字符编码过滤器 REST 过滤器

​ 创建Spring的配置文件: applicationContext.xml:组件扫描、 连接池、 事务…

​ 创建Springmvc的配置文件: springmvc.xml : 组件扫描、 视图解析器 mvc:...

(3)MyBatis

​ 创建MyBatis的全局配置文件

​ 编写实体类 Mapper接口 Mapper映射文件

(4)Spring + MyBatis

​ MyBatis的 SqlSession的创建 .

​ MyBatis的 Mapper接口的代理实现类

(5)测试: REST CRUD

​ 查询所有的员工信息,列表显示

3、整合的配置

3.1 web.xml


<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">
 
 <filter>
 	<filter-name>CharacterEncodingFilterfilter-name>
 	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
 	<init-param>
 		<param-name>encodingparam-name>
 		<param-value>UTF-8param-value>
 	init-param>
 filter>
 <filter-mapping>
 	<filter-name>CharacterEncodingFilterfilter-name>
 	<url-pattern>/*url-pattern>
 filter-mapping>
 
 
 <filter>
 	<filter-name>HiddenHttpMethodFilterfilter-name>
 	<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
 filter>
 <filter-mapping>
 	<filter-name>HiddenHttpMethodFilterfilter-name>
 	<url-pattern>/*url-pattern>
 filter-mapping>
 

	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:applicationContext.xmlparam-value>
	context-param>

	<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
 
 
	<servlet>
		<servlet-name>springDispatcherServletservlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
		<init-param>
			<param-name>contextConfigLocationparam-name>
			<param-value>classpath:springmvc.xmlparam-value>
		init-param>
		<load-on-startup>1load-on-startup>
	servlet>
	<servlet-mapping>
		<servlet-name>springDispatcherServletservlet-name>
		<url-pattern>/url-pattern>
	servlet-mapping>
web-app>

3.2 Spring 配置



<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-spring="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="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.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
	
	
	<context:component-scan base-package="com.baidu.ssm">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	context:component-scan>
	
	
	<context:property-placeholder location="classpath:db.properties"/>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driver}">property>
		<property name="jdbcUrl" value="${jdbc.url}">property>
		<property name="user" value="${jdbc.username}">property>
		<property name="password" value="${jdbc.password}">property>
		
	bean>
	
	
	<bean id="dataSourceTransactionManager" 
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource">property>
	bean>
	<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
beans>

3.3 SpringMVC配置


<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.0.xsd
		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.0.xsd">
  
  <context:component-scan base-package="com.baidu.ssm" use-default-filters="false">
	  <context:include-filter type="annotation" 
         expression="org.springframework.stereotype.Controller"/>
  context:component-scan>
   
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/views/">property>
	<property name="suffix" value=".jsp">property>
   bean>

   <mvc:default-servlet-handler/>
   <mvc:annotation-driven/>
beans>

3.4 MyBatis配置



<configuration>
	
	 
	   <settings>
	 	
	 	<setting name="mapUnderscoreToCamelCase" value="true"/>
	 	
	 	<setting name="jdbcTypeForNull" value="NULL"/>
	 	
	 	<setting name="lazyLoadingEnabled" value="true"/>
	 	
	 	<setting name="aggressiveLazyLoading" value="false"/>	
	 	
	 	<setting name="cacheEnabled" value="true"/>
	 settings>
configuration>

3.5 Spring整合Mybatis配置


	
	
		
		
		
		
		
		
		
	
	
	
		
	
	


4、整合测试

(1)编写页面,发送请求:http://localhost:8080/ssm

(2)编写Handler,处理请求,完成响应

(3)在页面中获取数据,显示数据

5、整合案例(详细代码)

5.1 环境准备

(1)创建动态web工程并导入jar包

com.springsource.net.sf.cglib-2.2.0.jar

com.springsource.org.aopalliance-1.0.0.jar

com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar

spring-aop-4.0.0.RELEASE.jar

spring-aspects-4.0.0.RELEASE.jar

log4j.jar

mybatis-3.4.1.jar

mybatis-spring-1.3.0.jar

mysql-connector-java-5.1.37-bin.jar

druid-1.1.9.jar

jsqlparser-0.9.5.jar

pagehelper-5.0.0.jar

spring-beans-4.0.0.RELEASE.jar

spring-context-4.0.0.RELEASE.jar

spring-core-4.0.0.RELEASE.jar

spring-expression-4.0.0.RELEASE.jar

commons-logging-1.1.3.jarspring-jdbc-4.0.0.RELEASE.jar

spring-orm-4.0.0.RELEASE.jar

spring-tx-4.0.0.RELEASE.jar

spring-web-4.0.0.RELEASE.jar

spring-webmvc-4.0.0.RELEASE.jar

taglibs-standard-impl-1.2.1.jar

taglibs-standard-spec-1.2.1.jar

(2)db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/study?characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
(3)log4j.xml


 
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
 
 <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
   <param name="Encoding" value="UTF-8" />
   <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m  (%F:%L) \n" />
   layout>
 appender>
 <logger name="java.sql">
   <level value="debug" />
 logger>
 <logger name="org.apache.ibatis">
   <level value="info" />
 logger>
 <root>
   <level value="debug" />
   <appender-ref ref="STDOUT" />
 root>
log4j:configuration>

5.2 配置web.xml文件


<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">
 	
	<filter>
		<filter-name>characterEncodingFilterfilter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
		
		<init-param>
			<param-name>encodingparam-name>
			<param-value>utf-8param-value>
		init-param>
		
		<init-param>
			<param-name>forceEncodingparam-name>
			<param-value>trueparam-value>
		init-param>
	filter>
	<filter-mapping>
		<filter-name>characterEncodingFilterfilter-name>
		<url-pattern>/*url-pattern>
	filter-mapping>
	
	<filter>
		<filter-name>hiddenHttpMethodFilterfilter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
	filter>
	<filter-mapping>
		<filter-name>hiddenHttpMethodFilterfilter-name>
		<url-pattern>/*url-pattern>
	filter-mapping>
	
	
	<context-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:applicationContext.xmlparam-value>
	context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>
	
	
	<servlet>
		<servlet-name>springDispatcherServletservlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
		<init-param>
			<param-name>contextConfigLocationparam-name>
			<param-value>classpath:spring-mvc.xmlparam-value>
		init-param>
		<load-on-startup>1load-on-startup>
	servlet>

	<servlet-mapping>
		<servlet-name>springDispatcherServletservlet-name>
		<url-pattern>/url-pattern>
	servlet-mapping>
web-app>

5.3 Javabean

package com.baidu.ssm.beans;

public class Employee {
	private Integer id;
	private String lastName;
	private String gender;
	private String descr;
	
	private Department dept;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getDescr() {
		return descr;
	}

	public void setDescr(String descr) {
		this.descr = descr;
	}

	public Department getDept() {
		return dept;
	}

	public void setDept(Department dept) {
		this.dept = dept;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", lastName=" + lastName + ", gender=" + gender + ", descr=" + descr + ", dept="
				+ dept + "]";
	}
	
	
}

package com.baidu.ssm.beans;

public class Department {
	
	private Integer id;
	private String deptName;
	
	
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getDeptName() {
		return deptName;
	}
	public void setDeptName(String deptName) {
		this.deptName = deptName;
	}
	@Override
	public String toString() {
		return "Department [id=" + id + ", deptName=" + deptName + "]";
	}
	
	
}

5.4 mapper层(dao层)

package com.baidu.ssm.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.baidu.ssm.beans.Employee;
@Repository
public interface EmployeeMapper {
	
	/**
	 * 查询所有员工的信息以及部门的信息
	 */
	List<Employee>  getEmployeeAll();

}

5.5 配置SQL映射文件



<mapper namespace="com.baidu.ssm.mapper.EmployeeMapper">
  	<select id="getEmployeeAll" resultMap="getAll">
  		select e.id eid,last_name,gender,descr,e.dept_id,d.dept_name
  		from tbl_employee e,tbl_department d
  		where e.dept_id = d.id
  	
  	select>
  	
  	<resultMap type="employee" id="getAll">
  		<id column="eid" property="id"/>
  		<result column="last_name" property="lastName"/>
  		<result column="gender" property="gender"/>
  		<result column="descr" property="descr"/>
  		<association property="dept" javaType="department">
  			<id column="id" property="id"/>
  			<result column="dept_name" property="deptName"/>
  		association>
  	
  	resultMap>
mapper>

5.6 service层

package com.baidu.ssm.service;

import java.util.List;

import com.baidu.ssm.beans.Employee;

public interface EmployeeService {
	
	List<Employee> getEmployeeAll();
}

package com.baidu.ssm.service.impl;

import java.util.List;

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

import com.baidu.ssm.beans.Employee;
import com.baidu.ssm.mapper.EmployeeMapper;
import com.baidu.ssm.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService{

	@Autowired
	private EmployeeMapper employeeMapper;
	
	
	@Override
	public List<Employee> getEmployeeAll() {
		return employeeMapper.getEmployeeAll();
	}
	
	
}

5.7 controller层

package com.baidu.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.baidu.ssm.beans.Employee;
import com.baidu.ssm.service.EmployeeService;

@Controller
public class EmployeeController {
	
	@Autowired
	private EmployeeService employeeService;
	
	@RequestMapping(value="emps",method=RequestMethod.GET)
	public String getAllEmps(Model model) {
		
		//调用service层的方法
		List<Employee> emps = employeeService.getEmployeeAll();
		
		//将查询到的emps模型数据添加到model中
		model.addAttribute("emps", emps);
		return "list";
	}
}

5.8 配置applicationContext.xml文件


<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"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		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.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	
	
	<context:component-scan base-package="com.baidu.ssm">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	context:component-scan>
	
	<context:property-placeholder location="classpath:db.properties"/>
	
	
	
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName" value="${jdbc.driver}"/>
		<property name="url" value="${jdbc.url}"/>
		<property name="username" value="${jdbc.username}"/>
		<property name="password" value="${jdbc.password}"/>	
	bean>
	
	<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	bean>
	
	<tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>
	
	
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<property name="dataSource" ref="dataSource">property>
		
		
		<property name="configLocation" value="classpath:mybatis-conf.xml"/>
		
		
		
	bean>
	
	
	<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.baidu.ssm.mapper">property>
	bean>
	
beans>

5.9 配置spring-mvc.xml文件


<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.0.xsd
		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.0.xsd">

	
	<context:component-scan base-package="com.baidu.ssm" use-default-filters="false">
	
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	context:component-scan>
	
	
	<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"/>
		<property name="suffix" value=".jsp"/>
	bean>
	
	
	<mvc:default-servlet-handler/>
	
	
	<mvc:annotation-driven/>

beans>

5.10 配置mybatis的主配置文件




<configuration>
	

	<settings>
		
		<setting name="mapUnderscoreToCamelCase" value="true"/>
		
		<setting name="lazyLoadingEnabled" value="true"/>
		
		<setting name="aggressiveLazyLoading" value="false"/>
	settings>
	
	
	<typeAliases>
		
		
		<package name="com.baidu.ssm.beans"/>
	typeAliases>

	
	
			
	<mappers>
		
		
		<package name="com.baidu.ssm.mapper"/>
	mappers>
	
configuration>

5.11 创建index.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




人事管理系统的入口



	

欢迎来到人事管理系统页面


进入人事管理系统

5.12 创建list.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




Insert title here


	

欢迎进入人事管理系统



所有员工进行显示

员工编号 员工姓名 员工性别 员工描述 所在部门 操作
${emp.id} ${emp.lastName} ${emp.gender} ${emp.descr } ${emp.dept.deptName} 修改 删除
添加员工

5.13 效果

Spring+SpringMVC+Mybatis—三个框架(SSM)整合_第1张图片

你可能感兴趣的:(SSM框架)