一、简单理解

Spring、Spring MVC和MyBatis的整合主要原理就是将我们在单独使用Spring MVC和MyBatis过程中需要自己实例化的类都交由Ioc容器来管理,过程分为两步:

第一步整合Spring和Spring MVC,前提是项目已单独配置Spring和Spring MVC且能正常运行,主要步骤为先在项目中创建对应的service接口和它们的实现类,并通过注解实现类和在Spring配置文件中开启注解扫描的方式将接口实现类交由Ioc容器管理。接着在Controller响应请求的类中添加接口为成员变量,并且也通过注解的方式将其交由Ioc容器管理,最后,我们需要把Spring配置文件的加载设置为项目启动时,这里通过在web.xml文件中配置Spring监听器实现,至此就可以实现Spring和Spring MVC的整合。

第二整合Spring和MyBatis,前提也是项目已单独配置Spring和MyBatis且能正常运行,这里需要导入额外的jar包mybatis-spring.jar,这里的版本需要根据MyBatis版本来确认,且本项目通过c3p0来配置数据库连接池,也需要导入c3p0的jar包。主要步骤为先将MyBatis配置文件中的内容(配置连接池部分)转移到Spring配置文件中(原先的MyBatis配置文件也就可以删除了),并且在Spring配置文件中配置SqlSessionFactroy工厂和sql语句对应接口所在包,这也就是将工厂和接口都交由Ioc容器管理,至此就可以实现Spring和MyBatis的整合。

二、代码展示

1.配置文件

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>SSMProject</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <!-- 配置Spring监听器,默认加载WEB-INF目录下的applicationContext.xml配置文件 -->
<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> <!-- 前端控制器 -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置Spring MVC配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 表示容器在启动时立即加载dispatcherServlet -->
<load-on-startup>1</load-on-startup>
</servlet> <!-- 让Spring MVC控制器拦截前端所有请求 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</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>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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

applicationContext.xml(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"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 开启注解扫描,非controller -->
<context:component-scan base-package="com.yh">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan> <!-- Spring整合MyBatis -->
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<!-- 驱动类名 -->
<property name="jdbcUrl"
value="jdbc:sqlserver://127.0.0.1:1433;databaseName=onlineshoppingmall" /><!--
url访问地址 -->
<property name="user" value="sa" /><!-- 链接数据库的用户名 -->
<property name="password" value="12345yehuan" /><!-- 链接数据库的密码 -->
<property name="initialPoolSize" value="10" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<property name="maxIdleTime" value="0" />
</bean>
<!-- 配置SqlSessionFactroy工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置接口所在包 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.yh.mybatis.mapper"></property>
</bean>
<!-- 配置Spring框架声明式事务管理 -->
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置事务通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!-- 配置AOP增强 -->
<aop:config>
<aop:pointcut expression="execution(* com.yh.service.*.*(..))" id="txPoint"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/>
</aop:config>
</beans>

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: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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 开启注解扫描,只扫描controller注解 -->
<context:component-scan base-package="com.yh.controller">
<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="" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean> <!-- 解决访问html等其他资源404 -->
<mvc:default-servlet-handler /> <!-- 开启SpringMVC注解支持 -->
<mvc:annotation-driven /> </beans>

2.service接口和它的实现类

AddressService.java

package com.yh.service;

import java.util.List;

import com.yh.entity.Address;

public interface AddressService {

    int addAddress(Address address);

    List<Address> loadAddress();

}

AddressServiceImpl.java

package com.yh.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.yh.entity.Address;
import com.yh.mybatis.mapper.AddressMapper;
import com.yh.service.AddressService; @Service("addressService")
public class AddressServiceImpl implements AddressService { @Autowired
private AddressMapper am; @Override
public int addAddress(Address address) {
return am.addAddress(address);
} @Override
public List<Address> loadAddress() {
System.out.println("业务层查找地址信息");
return am.loadAddress();
} }

3.MyBatis的sql语句配置文件和接口

AddressMapper.xml

<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yh.mybatis.mapper.AddressMapper"> <select id="loadAddress" resultType="com.yh.entity.Address">
select* from address
</select> <insert id="addAddress" parameterType="com.yh.entity.Address">
insert into address
(buyerid,consignee)values(#{buyerId},#{consignee})
</insert> </mapper>

AddressMapper.java

package com.yh.mybatis.mapper;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.yh.entity.Address;

@Repository
public interface AddressMapper { int addAddress(Address address); List<Address> loadAddress();
}

4.响应前端请求的Controller类

AddressController.java

package com.yh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import com.yh.entity.Address;
import com.yh.service.AddressService; @Controller
@RequestMapping(value = "/address")
public class AddressController { @Autowired
private AddressService addressService; @ResponseBody
@RequestMapping(value = "/loadAddress", produces = "application/json; charset=utf-8")
public String loadAddress() {
System.out.println("表现层查询所有地址");
Address addr = new Address();
addr.setBuyerId(99);
addr.setConsignee("叶欢");
int result = addressService.addAddress(addr);
System.out.println(result != 0 ? "成功" : "失败");
return null;
} }

5实体类

Address.java

package com.yh.entity;

import java.io.Serializable;

public class Address implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int buyerId;
private String consignee;public int getBuyerId() {
return buyerId;
} public void setBuyerId(int buyerId) {
this.buyerId = buyerId;
} public String getConsignee() {
return consignee;
} public void setConsignee(String consignee) {
this.consignee = consignee;
} @Override
public String toString() {
return "Address [addressId=" + addressId + ", buyerId=" + buyerId + ", consignee=" + consignee + ", telephone="
+ telephone + ", detail=" + detail + ", defaultAddress=" + defaultAddress + "]";
}
}

最基础的SSM框架整合篇的更多相关文章

  1. SSM框架整合篇

    目录 SSM整合 框架搭建步骤 SSM整合 Author:SimpleWu github(已上传SSMrest风格简单增删该查实例):https://gitlab.com/450255266/code ...

  2. SSM框架整合环境构建——基于Spring4和Mybatis3

    目录 环境 配置说明 所需jar包 配置db.properties 配置log4j.properties 配置spring.xml 配置mybatis-spring.xml 配置springmvc.x ...

  3. SpringMVC--从理解SpringMVC执行流程到SSM框架整合

    前言 SpringMVC框架是SSM框架中继Spring另一个重要的框架,那么什么是SpringMVC,如何用SpringMVC来整合SSM框架呢?下面让我们详细的了解一下. 注:在学习SpringM ...

  4. SpringMVC札集(10)——SSM框架整合

    自定义View系列教程00–推翻自己和过往,重学自定义View 自定义View系列教程01–常用工具介绍 自定义View系列教程02–onMeasure源码详尽分析 自定义View系列教程03–onL ...

  5. ssm框架整合-过程总结(第二次周总结)

    距离上次写博客已经有4.5天的时间了. 这次写博客目的是总结一下项目开始到现在,过程中遇到的问题.和学到的知识.经验. 初略总结下自己从中学到的: Spring :在学习中被反复强调的Ioc(反转控制 ...

  6. SSM框架整合项目 :租房管理系统

    使用ssm框架整合,oracle数据库 框架: Spring SpringMVC MyBatis 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastj ...

  7. 基于maven的ssm框架整合

    基于maven的ssm框架整合 第一步:通过maven建立一个web项目.                第二步:pom文件导入jar包                              (1 ...

  8. JavaWeb之ssm框架整合,用户角色权限管理

    SSM框架整合 Spring SpringMVC MyBatis 导包: 1, spring 2, MyBatis 3, mybatis-spring 4, fastjson 5, aspectwea ...

  9. springmvc(二) ssm框架整合的各种配置

    ssm:springmvc.spring.mybatis这三个框架的整合,有耐心一步步走. --WH 一.SSM框架整合 1.1.整合思路 从底层整合起,也就是先整合mybatis与spring,然后 ...

随机推荐

  1. c++学习笔记(十一)

    函数重载(overloading) 概念 重载函数是函数的一种特殊情况,为方便使用,C++允许在同一范围中声明几个功能类似的同名函数,但是这些同名函数的形式参数(指参数的个数.类型或者顺序)必须不同, ...

  2. Django笔记&教程 3-3 模板常用语法

    Django 自学笔记兼学习教程第3章第3节--模板常用语法 点击查看教程总目录 本文主要参考:https://docs.djangoproject.com/en/2.2/ref/templates/ ...

  3. Solon 1.5.67 发布,增加 GraalVm Native 支持

    Solon 已有120个生态扩展插件,此次更新主要为细节打磨: 添加 solon.extend.graalvm 插件,用于适配 graalvm native image 模式 从此,solon 进入 ...

  4. jenkins-发送allure邮件测试报告

    1.安装插件 allure-jenkins-plugin  2.在全局工具配置中,配置allure命令行 3.全局工具配置中,添加JDK配置 4.配置slave节点工具(JDK+Allure)-配置在 ...

  5. 【从零开始学习Node.js】一.在CentOS 7中部署Node.js环境

    一.背景信息 Node.js是一个基于Chrome V8引擎的JavaScript运行环境,用来方便快速地搭建易于扩展的网络应用.Node.js使用了一个事件驱动.非阻塞式I/O的模型,使其轻量又高效 ...

  6. win10 如何查看本地连接的WIFI密码

    1 在状态栏右侧找到WIFI图标,右键WIFI图标,打开"网路和 Internet"设置 2 切换到 "状态"或"WLAN",找到" ...

  7. mybatis判断集合长度

    使用mybatis框架在写sql的时候碰到一个异常: 1064 - You have an error in your SQL syntax; check the manual that corres ...

  8. 【NOIP 2018】摆渡车

    前情提要 是的 我终于回来补坑了 一年了哇 你这个鸽子王 斜率优化版本 今天在复习斜率优化的时候才想起来这个题 定义就不设了 大家想看可以看上面那个原版 怎么斜率优化呢? 我们考虑\(i\)点是当前的 ...

  9. 【GS文献】全基因组选择模型研究进展及展望

    目录 1. GS概况 2. GS模型 1)直接法 GBLUP 直接法的模型改进 ①单随机效应 ②多随机效应 2)间接法 间接法模型 基于间接法的模型改进 3. GS模型比较 模型比较结论 4.问题及展 ...

  10. Mysql查询优化汇总 order by优化例子,group by优化例子,limit优化例子,优化建议

    Mysql查询优化汇总 order by优化例子,group by优化例子,limit优化例子,优化建议 索引 索引是一种存储引擎快速查询记录的一种数据结构. 注意 MYSQL一次查询只能使用一个索引 ...