Spring + SpringMVC + Mybatis整合流程

1      需求

  1.1     客户列表查询

  1.2     根据客户姓名模糊查询

2      整合思路

第一步:整合dao层

Mybatis和spring整合,通过spring管理mapper接口,使用mapper扫描器自动扫描mapper接口,并在spring中进行注册。

第二步:整合service层

通过spring管理service层,service调用mapper接口。使用配置方式将service接口配置在spring配置文件中,并且进行事务控制。

第三步:整合springMVC

由于springMVC是spring的模块,不需要整合。

3      准备环境

3.1     数据库版本
    mysql5.7

3.2     编译器
    eclipse

3.3     Jar 包

3.3.1     spring的jar包

3.3.2     spring与mybatis的整合jar包

3.3.3     mybatis的jar包

3.3.4     数据库驱动包

3.3.5     log4j包

3.3.6     log4j配置文件

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n ### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:\mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

3.3.7     dbcp数据库连接池包

3.3.8     jstl包

4      整合dao

4.1      sqlMapconfig.xml

mybatis的配置文件:

<?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><!-- 定义别名 --><typeAliases><package name="com.haohan.ssm.po" /></typeAliases><!-- 配置mapper映射文件 --><mappers><!-- 加载 原始dao使用映射文件 --><!-- <mapper resource="sqlmap/User.xml" /> --     <!--批量mapper扫描 遵循规则:将mapper.xml和mapper.java文件放在一个目录 且文件名相同 ,现在由spring配置扫描--><!-- <package name="cn.itcast.ssm.dao.mapper" /> --></mappers>
</configuration>

4.2      db.properties数据库配置文件

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/haohan1?characterEncoding=utf8&useSSL=false
jdbc.username=root
jdbc.password=123456

4.3     applicationContext-dao.xml

spring在这个xml文件中配置dbcp连接池,sqlSessionFactory,mapper的批量扫描。

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!--1. 数据源 --><!-- 加载配置文件 --><context:property-placeholder location="classpath:db.properties"/><!-- 配置dbcp连接池 --><bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"destroy-method="close"><property name="driverClassName" value="${jdbc.driver}"></property>  <property name="url" value="${jdbc.url}"></property><property name="username" value="${jdbc.name}"></property><property name="password" value="${jdbc.password}"</property></bean><!--2. sqlSessionFactory --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml"></property><property name="dataSource" ref="dataSource"></property></bean><!-- 3. mapper的批量扫描--><!-- mapper的批量扫描 :从mapper包中扫描mapper接口,自动创建代理对象并且在spring容器中注册。遵循的规范:需要将mapper的接口类名和mapper.xml映射文件名保持一致,且在一个目录中。自动扫描出来的mapper的bean的id为mapper类名(首字母小写)--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 指定扫描的包名如果扫描多个包,用半角逗号分开--><property name="basePackage" value="cn.haohan.ssm.mapper"></property><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property></bean>
</beans>

4.4     逆向工程生成po类和mapper接口和mapper.xml文件

参考:http://how2j.cn/k/mybatis/mybatis-generator/1376.html

生成如下图的文件:

4.5     自定义mapper接口和xml文件,以及po的包装类

4.5.1     CustomMapper.java

public interface CustomMapper {public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

4.5.1     CustomMapper.xml

<?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">
<!-- namespace:命名空间,作用是对sql进行分类化管理,sql隔离 -->
<mapper namespace="cn.haohan.ssm.mapper.CustomMapper"><sql id="query_custom_where"><if test="hhCustom!=null"><if test="hhCustom.name!=null and hhCustom.name!=''">name like '%${hhCustom.name}%'</if></if></sql><resultMap type="hhCustom" id="hhCustomResultMap"><id column="id" property="id"/><result column="phone_number" property="phoneNumber"/></resultMap><select id="findAllCustom" parameterType="cn.haohan.ssm.po.HhCustomVo" resultMap="hhCustomResultMap">SELECT* FROM hh_custom<where><include refid="query_custom_where"></include></where></select>
</mapper>

4.5.2     HhCustomVo

//客户的包装类
public class HhCustomVo {//客户信息private HhCustom hhCustom;public HhCustom getHhCustom() {return hhCustom;}public void setHhCustom(HhCustom hhCustom) {this.hhCustom = hhCustom;}
}

4.6     数据库表结构

5      整合service

5.1     定义service接口

public interface CustomService {public HhCustom findCustomById(Integer id)throws Exception;public List<HhCustom> findAllCustom(HhCustomVo hhCustomVo)throws Exception;
}

5.2     service接口实现

public class CustomServiceImpl implements CustomService{@AutowiredHhCustomMapper hhCustomMapper;@AutowiredCustomMapper customMapper;@Overridepublic HhCustom findCustomById(Integer id) throws Exception {// TODO Auto-generated method stubreturn hhCustomMapper.selectByPrimaryKey(id);}@Overridepublic List<HhCustom> findAllCustom(HhCustomVo hhCustomVo) throws Exception {// TODO Auto-generated method stubreturn customMapper.findAllCustom(hhCustomVo);}
}

5.3     在spring容器配置service(applicationContext-service)

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><bean id="CustomServiceImpl" class="cn.haohan.ssm.service.impl.CustomServiceImpl"></bean>
</beans>

5.4   事务控制(applicationContext-transaction)

<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsd"><!-- 配置事务管理器对mybatis操作数据库事务控制,spring使用jdbc事务控制类--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!-- 配置数据源 --><property name="dataSource" ref="dataSource"></property></bean><!-- 配置事务增强(通知) --><tx:advice id="txadvice" transaction-manager="transactionManager"><tx:attributes><!-- 设置进行事务操作的方法匹配规则 --><tx:method name="save*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="find*" propagation="SUPPORTS"/><tx:method name="get*" propagation="SUPPORTS"/><tx:method name="select*" propagation="SUPPORTS"/></tx:attributes></tx:advice><!-- aop操作 --><aop:config><aop:advisor advice-ref="txadvice" pointcut="execution(* cn.haohan.ssm.serivce.impl.*.*(..))"/></aop:config>
</beans> 

6      整合springMVC

6.1      springmvc.xml

在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:context="http://www.springframework.org/schema/context"xmlns:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:mvc="http://www.springframework.org/schema/mvc"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 扫描加载handler --><context:component-scan base-package="cn.haohan.ssm.controller"></context:component-scan><!-- 注解映射器 --><!--<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>注解适配器<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> --><!-- 使用mvc:annotation-driven可代替上面的注解映射器和注解适配器mvc:annotation-driven默认加载许多参数绑定,比如json转换解析器,实际开发用mvc:annotation-driven--><mvc:annotation-driven> </mvc:annotation-driven><!-- 视图解析器解析jsp,默认使用jstl标签,--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/WEB-INF/jsp/"></property><property name="suffix" value=".jsp"></property></bean>
</beans>

6.2     配置前端控制器(web.xml)

<!-- 配置springmvc前端控制器 --><servlet><servlet-name>springmvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><!-- contextConfigLocation:加载springmvc的配置文件(配置处理器适配器、映射器、视图解析器默认加载的是/WEB-INF/servlet名称-servlet.xml( springmvc-servlet.xml)--><param-name>contextConfigLocation</param-name><param-value>classpath:spring/springmvc.xml</param-value></init-param></servlet><servlet-mapping><!--第一种:*.action ,访问以.action结尾的,由DispatcherServlet解析。第二种:/ ,所有访问的地址都由DispatcherServlet解析,对于静态文件需要配置不让DispatcherServlet解析。可以实现Restful风格。--><servlet-name>springmvc</servlet-name><url-pattern>*.action</url-pattern></servlet-mapping>

6.3     编写controller

@Controller
public class CustomController {@AutowiredCustomService customService;//模糊查询客户@RequestMapping("/findAllCustom")public ModelAndView findAllCustom(HhCustomVo hhCustomVo) throws Exception {List<HhCustom> customlist = customService.findAllCustom(hhCustomVo);ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("customlist", customlist);modelAndView.setViewName("customlist");return modelAndView;}//根据客户id查询public ModelAndView findCustomByid(Integer id) throws Exception {HhCustom hhCustom = customService.findCustomById(id);ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("hhCustom", hhCustom);modelAndView.setViewName("customlist");return modelAndView;}
}

6.4     编写jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>客戶列表</title>
</head>
<body><form name="customForm"action="${pageContext.request.contextPath}/findAllCustom.action"method="post">查询条件:<table width="100%" border=1><tr><td>客戶名称:<input name="hhCustom.name" /></td><%-- <td>客戶类型: <select name="customType"><c:forEach items="${customType}" var="customType"><option value="${customType.key }">${customType.value}</option></c:forEach></select></td> --%><td><button type="submit" value="查询" >查询</button></td></tr></table>客戶列表:<table width="100%" border=1><tr><th>选择</th><th>客戶名称</th><th>客戶邮箱</th><th>客戶电话</th><th>客户类型</th><!-- <th>操作</th> --></tr><c:forEach items="${customlist}" var="custom"><tr><td><input type="checkbox" name="custom_id" value="${custom.id}" /></td><td>${custom.name }</td><td>${custom.mail }</td><td>${custom.phoneNumber }</td><td>${custom.category }</td><%--<td><fmt:formatDate value="${custom.birthday }" pattern="yyyy-MM-dd HH:mm:ss"/></td><td><a href="${pageContext.request.contextPath }/items/editItems.action?id=${item.id }">修改</a></td> --%></tr></c:forEach></table></form>
</body>
</html>

7      加载spring容器(web.xml)

<!-- 加载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>

8      Post方法中文乱码(web.xml)

<!-- post中文乱码 --><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></filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>

9      结果

9.1     客户查询列表

9.2     根据模糊

转载于:https://www.cnblogs.com/peter-hao/p/ssm.html

ssm框架搭建和整合流程相关推荐

  1. ssm框架连接mysql数据库的具体步骤_ssm框架搭建和整合流程

    Spring + SpringMVC + Mybatis整合流程 1      需求 1.1     客户列表查询 1.2     根据客户姓名模糊查询 2      整合思路 第一步:整合dao层 ...

  2. SSM框架搭建思路及流程

    SSM框架也就是SpringMVC+Spring+Mybatis来实现WEB层,Service层和Dao层的整合 搭建SSM框架主要就是完成相关文件的配置 整个步骤如下: 一.导入jar包 由于spr ...

  3. SSM框架搭建(三)--整合p6spy

    强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan 描述 普通情况下,控制台打印出的sql是带?的,开发人员在自己调试的过程中遇到bug是再常见不过 ...

  4. 小菜鸟的SSM框架搭建【详细步骤】【SSM/IDEA/MAVEN】

    小菜鸟的SSM框架搭建 内容很长噢,一步步搭建 此框架是跟着b站上的黎曼的猜想所发布的视频搭建起来的,细节操作可以看视频.我只是在这里梳理一下ssm框架搭建的流程. 整合说明:SSM整合可以使用多种方 ...

  5. ssm框架搭建连接mysql_从零开始搭建SSM框架(Spring + Spring MVC + Mybatis)

    最近在回顾和总结一些技术,想到了把之前比较火的 SSM 框架重新搭建出来,作为一个小结,同时也希望本文章写出来能对大家有一些帮助和启发,因本人水平有限,难免可能会有一些不对之处,欢迎各位大神拍砖指教, ...

  6. javaweb成长之路:SSM框架搭建

    学习javaweb开发,框架的学习是难以避免的,合理的使用框架进行开发,可以很大程度的提升开发效率,减少开发者的工作量.随着it行业的不断发展,各种框架也是层出不穷,目前使用最广的框架应该是属于ssm ...

  7. SSM框架搭建详细解析

    总结了一下搭建SSM框架流程,在以后用到的时候方便回头使用. 使用工具:MyEclipse 2015:Tomcat 8版本:jdk1.8版本. 首先: 1:创建一个WebProject项目,jdk1. ...

  8. SSM框架搭建,及遇到的问题

    SSM框架搭建,及遇到的问题 1.基本概念 1.1.Spring Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Exp ...

  9. java二维码生成 使用SSM框架 搭建属于自己的APP二维码合成、解析、下载

    java二维码生成 使用SSM框架 搭建属于自己的APP二维码合成.解析.下载 自己用java搭建一个属于自己APP二维码合成网站.我的思路是这样的: 1.用户在前台表单提交APP的IOS和Andro ...

最新文章

  1. Piccure Plus 3.1中文汉化版,Piccure Plus 3.1破解版,模糊照片变清晰神器,让你不再害怕手抖了
  2. gzez某蒟蒻lyy的博客
  3. JAVA系统和DOMINO通过LDAP集成方
  4. Linux进程详细信息查看
  5. jdk1.8 mysql_Centos 7配置JDK1.8+MySQL5.7+Tomcat 8 开发环境
  6. verilog学习(1)基本语法
  7. HMAC加密的消息摘要码
  8. 电子政务的着力点---紫云舆情服务
  9. boost升压电路遇到过的问题
  10. mybatis常用标签
  11. html 怎么插入向上的箭头,如何在html中插入箭头?
  12. 扫地机器人噪音响_硬件老兵拆机分析:扫地机器人噪音大小到底与何相关?
  13. 韩团god朴俊亨迎娶小13岁空姐 成员唱祝歌
  14. for(;;)和while(true)都是无条件循环
  15. matlab wind回测,[转载]基于Matlab和Wind SQL数据库的通用选股策略回测程序
  16. 【github】Support for password authentication was removed on August 13,2021.
  17. 暑假阅读的正确打开方式原来这么简单!
  18. 虚拟机ifconfig后显示ip过多,无法查看本机ip或看不到全部ip
  19. 用ado打开Excel文件时报外部表不是预期的格式的解决方法
  20. 产品周报第32期|CSDN APP V5.3.0发布:新增3款桌面小组件,签到页新增提升原力分引导

热门文章

  1. 如何简化临时内存的分配与释放
  2. 用grub4dos修复grub
  3. Delphi2010组件/控件安装方法
  4. docker desktop一直starting不变化
  5. 自动局部变量 与 静态局部变量 的区别与用途
  6. session或者error引起的iframe嵌套问题的解决
  7. 《x86汇编语言:从实模式到保护模式》视频来了
  8. 五分钟了解先验概率和后验概率
  9. JZOJ 5068. 【GDSOI2017第二轮模拟】树
  10. JZOJ 3853. 【NOIP2014八校联考第2场第2试9.28】帮助Bsny(help)