小言_互联网的博客

Spring、SpringMvc、MyBatis整合案例

434人阅读  评论(0)

前言:

Spring、SpringMvc、MyBatis各框架都学了一段时间了,现在综合起来做一个小案例。案例内容:查询所有账户列表以及通过表单保存账户。通过此案例,进一步理解各框架的应用以及熟悉整合过程中的一些列配置。

步骤:


  
  1. 搭建整合环境
  2. 整合说明:
  3. 此案例选择XML + 注解的方式
  4. 整合的思路:
  5. 1. 先搭建整合的环境
  6. 2. 再使用Spring整合SpringMVC框架
  7. 3. 最后使用Spring整合MyBatis框架


一、创建account数据库表


  
  1. create table account(
  2. id int primary key auto_increment,
  3. name varchar( 100),
  4. money double( 7, 2),
  5. );

 

二、创建一个maven项目

此处可以参考之前博客springMvc项目创建

导入maven坐标及相关的依赖


  
  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <maven.compiler.source>1.8</maven.compiler.source>
  4. <maven.compiler.target>1.8</maven.compiler.target>
  5. <spring.version>5.0.2.RELEASE</spring.version>
  6. <slf4j.version>1.6.6</slf4j.version>
  7. <log4j.version>1.2.12</log4j.version>
  8. <mysql.version>5.1.6</mysql.version>
  9. <mybatis.version>3.4.5</mybatis.version>
  10. </properties>
  11. <dependencies>
  12. <!-- spring -->
  13. <dependency>
  14. <groupId>org.aspectj</groupId>
  15. <artifactId>aspectjweaver</artifactId>
  16. <version>1.6.8</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework</groupId>
  20. <artifactId>spring-aop</artifactId>
  21. <version> ${spring.version}</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework</groupId>
  25. <artifactId>spring-context</artifactId>
  26. <version> ${spring.version}</version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework</groupId>
  30. <artifactId>spring-web</artifactId>
  31. <version> ${spring.version}</version>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework</groupId>
  35. <artifactId>spring-webmvc</artifactId>
  36. <version> ${spring.version}</version>
  37. </dependency>
  38. <dependency>
  39. <groupId>org.springframework</groupId>
  40. <artifactId>spring-test</artifactId>
  41. <version> ${spring.version}</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.springframework</groupId>
  45. <artifactId>spring-tx</artifactId>
  46. <version> ${spring.version}</version>
  47. </dependency>
  48. <dependency>
  49. <groupId>org.springframework</groupId>
  50. <artifactId>spring-jdbc</artifactId>
  51. <version> ${spring.version}</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>junit</groupId>
  55. <artifactId>junit</artifactId>
  56. <version>4.12</version>
  57. <scope>compile</scope>
  58. </dependency>
  59. <dependency>
  60. <groupId>mysql</groupId>
  61. <artifactId>mysql-connector-java</artifactId>
  62. <version> ${mysql.version}</version>
  63. </dependency>
  64. <dependency>
  65. <groupId>javax.servlet</groupId>
  66. <artifactId>servlet-api</artifactId>
  67. <version>2.5</version>
  68. <scope>provided</scope>
  69. </dependency>
  70. <dependency>
  71. <groupId>javax.servlet.jsp</groupId>
  72. <artifactId>jsp-api</artifactId>
  73. <version>2.0</version>
  74. <scope>provided</scope>
  75. </dependency>
  76. <dependency>
  77. <groupId>jstl</groupId>
  78. <artifactId>jstl</artifactId>
  79. <version>1.2</version>
  80. </dependency>
  81. <!-- log start -->
  82. <dependency>
  83. <groupId>log4j</groupId>
  84. <artifactId>log4j</artifactId>
  85. <version> ${log4j.version}</version>
  86. </dependency>
  87. <dependency>
  88. <groupId>org.slf4j</groupId>
  89. <artifactId>slf4j-api</artifactId>
  90. <version> ${slf4j.version}</version>
  91. </dependency>
  92. <dependency>
  93. <groupId>org.slf4j</groupId>
  94. <artifactId>slf4j-log4j12</artifactId>
  95. <version> ${slf4j.version}</version>
  96. </dependency>
  97. <!-- log end -->
  98. <dependency>
  99. <groupId>org.mybatis</groupId>
  100. <artifactId>mybatis</artifactId>
  101. <version> ${mybatis.version}</version>
  102. </dependency>
  103. <dependency>
  104. <groupId>org.mybatis</groupId>
  105. <artifactId>mybatis-spring</artifactId>
  106. <version>1.3.0</version>
  107. </dependency>
  108. <dependency>
  109. <groupId>c3p0</groupId>
  110. <artifactId>c3p0</artifactId>
  111. <version>0.9.1.2</version>
  112. < type>jar</ type>
  113. <scope>compile</scope>
  114. </dependency>
  115. </dependencies>


三、创建相应的实体类、表现层、服务层、持久层

实体类 Account


  
  1. package com.xiaojie.pojo;
  2. import java.io.Serializable;
  3. /**
  4. * @program: springmvc01_start
  5. * @description: 账户实体类
  6. * @author: Mr.Li
  7. * @create: 2020-04-21 22:52
  8. **/
  9. public class Account implements Serializable {
  10. private Integer id;
  11. private String name;
  12. private Double money;
  13. public Integer getId() {
  14. return id;
  15. }
  16. public void setId(Integer id) {
  17. this.id = id;
  18. }
  19. public String getName() {
  20. return name;
  21. }
  22. public void setName(String name) {
  23. this.name = name;
  24. }
  25. public Double getMoney() {
  26. return money;
  27. }
  28. public void setMoney(Double money) {
  29. this.money = money;
  30. }
  31. @Override
  32. public String toString() {
  33. return "Account{" +
  34. "id=" + id +
  35. ", name='" + name + '\'' +
  36. ", money=" + money +
  37. '}';
  38. }
  39. }

 

表现层:AccountController


  
  1. package com.xiaojie.controller;
  2. import com.xiaojie.pojo.Account;
  3. import com.xiaojie.service.AccountService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import java.io.IOException;
  11. import java.util.List;
  12. /**
  13. * @program: springmvc01_start
  14. * @description: 控制层
  15. * @author: Mr.Li
  16. * @create: 2020-04-21 23:28
  17. **/
  18. @Controller
  19. @RequestMapping( "/account")
  20. public class AccountController {
  21. @Autowired
  22. AccountService accountService;
  23. /**
  24. * 查询所有的数据
  25. * @return
  26. */
  27. @RequestMapping( "/findAll")
  28. public String findAll(Model model) {
  29. System.out.println( "表现层:查询所有账户...");
  30. List<Account> accounts = accountService.findAll();
  31. accounts.stream().forEach(account -> {
  32. System.out.println(account);
  33. });
  34. model.addAttribute( "accounts",accounts);
  35. return "list";
  36. }
  37. @RequestMapping( "/saveAccount")
  38. public void saveAccount(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
  39. System.out.println( "表现层:查询所有账户...");
  40. accountService.saveAccount(account);
  41. response.sendRedirect(request.getContextPath() + "/account/findAll");
  42. }
  43. }

 

持久层:AccountDao 

       基于注解方式实现


  
  1. package com.xiaojie.dao;
  2. import com.xiaojie.pojo.Account;
  3. import org.apache.ibatis.annotations.Insert;
  4. import org.apache.ibatis.annotations.Select;
  5. import org.springframework.stereotype.Repository;
  6. import java.util.List;
  7. @Repository
  8. public interface AccountDao {
  9. /**
  10. * 保存账户
  11. * @param account
  12. */
  13. @Insert( "insert into account (name,money) values(#{name},#{money})")
  14. public void saveAccount(Account account);
  15. /**
  16. * 获取账户列表
  17. * @return
  18. */
  19. @Select( "select * from account")
  20. public List<Account> findAll();
  21. }

 

服务层:接口AccountService

       实现类 AccountServiceImpl 


  
  1. package com.xiaojie.service;
  2. import com.xiaojie.pojo.Account;
  3. import java.util.List;
  4. public interface AccountService {
  5. /**
  6. * 保存账户
  7. * @param account
  8. */
  9. public void saveAccount(Account account);
  10. /**
  11. * 获取账户列表
  12. * @return
  13. */
  14. public List<Account> findAll();
  15. }

  
  1. package com.xiaojie.service.impl;
  2. import com.xiaojie.dao.AccountDao;
  3. import com.xiaojie.pojo.Account;
  4. import com.xiaojie.service.AccountService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. /**
  9. * @program: springmvc01_start
  10. * @description: 账户服务层
  11. * @author: Mr.Li
  12. * @create: 2020-04-21 22:57
  13. **/
  14. @Service( "accountService")
  15. public class AccountServiceImpl implements AccountService {
  16. @Autowired
  17. AccountDao accountDao;
  18. @Override
  19. public void saveAccount(Account account) {
  20. System.out.println( "业务层:查询所有账户...");
  21. accountDao.saveAccount(account);
  22. }
  23. @Override
  24. public List<Account> findAll() {
  25. System.out.println( "业务层:查询所有账户...");
  26. return accountDao.findAll();
  27. }
  28. }

 

四、spring整合SpringMVC、MyBatis框架

1、在resources文件中创建applicationContext.xml文件

在里面配置:注解扫描、连接池、SqlSession工厂、spring声明事务管理、aop


  
  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <beans xmlns= "http://www.springframework.org/schema/beans"
  3. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context= "http://www.springframework.org/schema/context"
  5. xmlns:aop= "http://www.springframework.org/schema/aop"
  6. xmlns:tx= "http://www.springframework.org/schema/tx"
  7. xsi:schemaLocation= "http://www.springframework.org/schema/beans
  8. http://www.springframework.org/schema/beans/spring-beans.xsd
  9. http://www.springframework.org/schema/context
  10. http://www.springframework.org/schema/context/spring-context.xsd
  11. http://www.springframework.org/schema/aop
  12. http://www.springframework.org/schema/aop/spring-aop.xsd
  13. http://www.springframework.org/schema/tx
  14. http://www.springframework.org/schema/tx/spring-tx.xsd">
  15. <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,
  16. 因为web层让SpringMVC框架去管理 -->
  17. <context:component-scan base-package= "com.xiaojie">
  18. <!--配置要忽略的注解-->
  19. <context:exclude-filter type= "annotation" expression= "org.springframework.stereotype.Controller"></context:exclude-filter>
  20. </context:component-scan>
  21. <!--配置c3p0连接池对象-->
  22. <bean id= "dateSource" class= "org.springframework.jdbc.datasource.DriverManagerDataSource">
  23. <property name= "driverClassName" value= "com.mysql.jdbc.Driver" />
  24. <property name= "url" value= "jdbc:mysql:///springtest" />
  25. <property name= "username" value= "root" />
  26. <property name= "password" value= "123456" />
  27. </bean>
  28. <!--配置SqlSession的工厂-->
  29. <bean id= "SqlSession" class= "org.mybatis.spring.SqlSessionFactoryBean">
  30. <property name= "dataSource" ref= "dateSource"></property>
  31. </bean>
  32. <!--配置扫描的dao包-->
  33. <bean id= "mapperScanner" class= "org.mybatis.spring.mapper.MapperScannerConfigurer">
  34. <property name= "basePackage" value= "com.xiaojie.dao"></property>
  35. </bean>
  36. <!--配置spring声明式事务管理-->
  37. <!--配置事务管理器-->
  38. <bean id= "transactionManager" class= "org.springframework.jdbc.datasource.DataSourceTransactionManager">
  39. <property name= "dataSource" ref= "dateSource"></property>
  40. </bean>
  41. <!--配置事务通知-->
  42. <tx:advice id= "txAdvice" transaction-manager= "transactionManager">
  43. <tx:attributes>
  44. <tx:method name= "find*" read-only= "true"/>
  45. <tx:method name= "*" isolation= "DEFAULT"></tx:method>
  46. </tx:attributes>
  47. </tx:advice>
  48. <!--配置aop增强-->
  49. <aop:config>
  50. <aop:advisor advice-ref= "txAdvice" pointcut= "execution(* com.xiaojie.service.impl.*ServiceImpl.*(..))"></aop:advisor>
  51. </aop:config>
  52. </beans>

 

2、在resources文件中创建springmvc.xml文件

在里面配置:前端的视图解析器、表现层的注解扫描、静态资源过滤等


  
  1. <?xml version= "1.0" encoding= "UTF-8"?>
  2. <beans xmlns= "http://www.springframework.org/schema/beans"
  3. xmlns:mvc= "http://www.springframework.org/schema/mvc"
  4. xmlns:context= "http://www.springframework.org/schema/context"
  5. xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation= "http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd">
  12. <!-- 扫描controller的注解,别的不扫描 -->
  13. <context:component-scan base-package= "com.xiaojie">
  14. <context:include-filter type= "annotation"
  15. expression= "org.springframework.stereotype.Controller"/>
  16. </context:component-scan>
  17. <!-- 配置视图解析器 -->
  18. <bean id= "viewResolver" class= "org.springframework.web.servlet.view.InternalResourceViewResolver">
  19. <!-- JSP文件所在的目录 -->
  20. <property name= "prefix" value= "/WEB-INF/pages/" />
  21. <!-- 文件的后缀名 -->
  22. <property name= "suffix" value= ".jsp" />
  23. </bean>
  24. <!-- 设置静态资源不过滤 -->
  25. <mvc:resources location= "/css/" mapping= "/css/**" />
  26. <mvc:resources location= "/images/" mapping= "/images/**" />
  27. <mvc:resources location= "/js/" mapping= "/js/**" />
  28. <!-- 开启对SpringMVC注解的支持 -->
  29. <mvc:annotation-driven />
  30. </beans>

 

3、web.xml中配置:

因为需要在项目启动的时候,就去加载applicationContext.xml、springmvc.xml的配置文件(上面配置的),所以需要在web.xml中配置ContextLoaderListener监听器、前端控制器、中文乱码过滤器等


  
  1. <! DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app>
  5. <display-name> Archetype Created Web Application</display-name>
  6. <!--配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件-->
  7. <servlet>
  8. <servlet-name>dispatcherServlet</servlet-name>
  9. <servlet- class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <!--配置初始化参数-->
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath:springmvc.xml</param-value>
  14. </init-param>
  15. <!--服务器启动的时候 ,让DispatcherServlet对象创建-->
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <servlet-mapping>
  19. <servlet-name>dispatcherServlet</servlet-name>
  20. <url-pattern>/</url-pattern>
  21. </servlet-mapping>
  22. <!-- 配置Spring的监听器 -->
  23. <listener>
  24. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  25. </listener>
  26. <!-- 配置加载类路径的配置文件 -->
  27. <context-param>
  28. <param-name>contextConfigLocation</param-name>
  29. <param-value>classpath:applicationContext.xml</param-value>
  30. </context-param>
  31. <!--配置解决中文乱码的过滤器-->
  32. <filter>
  33. <filter-name>characterEncodingFilter</filter-name>
  34. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  35. <init-param>
  36. <param-name>encoding</param-name>
  37. <param-value>UTF-8</param-value>
  38. </init-param>
  39. </filter>
  40. <filter-mapping>
  41. <filter-name>characterEncodingFilter</filter-name>
  42. <url-pattern>/*</url-pattern>
  43. </filter-mapping>
  44. </web-app>

 

五、编写jsp页面进行测试

webapp目录结构

1、index.jsp


  
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: ASUS
  4. Date: 2020/ 4/ 21
  5. Time: 23:28
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <html>
  10. <head>
  11. <title>Title </title>
  12. </head>
  13. <body>
  14. <a href="account/findAll">testFindAll </a>
  15. <h3>测试保存a </h3>
  16. <form action="account/saveAccount" method="post">
  17. 姓名: <input type="text" name="name"/> <br>
  18. 金额: <input type="text" name="money"/> <br>
  19. <input type="submit" value="保存"/> <br>
  20. </form>
  21. </body>
  22. </html>

 

lsit.jsp


  
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: ASUS
  4. Date: 2020/ 4/ 21
  5. Time: 23:29
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
  9. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  10. <html>
  11. <head>
  12. <title>Title </title>
  13. </head>
  14. <body>
  15. 查询成功!
  16. <table border="1" width="300px">
  17. <tr>
  18. <th>编号 </th>
  19. <th>账户名称 </th>
  20. <th>金额 </th>
  21. </tr>
  22. <c:forEach items="${accounts}" var="account">
  23. <tr>
  24. <td>${account.id} </td>
  25. <td>${account.name} </td>
  26. <td>${account.money} </td>
  27. </tr>
  28. </c:forEach>
  29. </table>
  30. </body>
  31. </html>

 

六、测试运行结果:

1、配置tomcat服务器,然后添加当前项目的war包

 

2、选择后点击应用,并启动服务

浏览器会看到首页内容

 

点击testFindAll后的页面

 

通过表单添加:

 

点击保存自动跳转查询页:

 

 

终于更到最后了。虽然案例简单,但还是记录一下自己的学习的一个过程吧,毕竟整合的过程还是很容易出错的。记录只是便于以后的一个回忆吧,希望大家养成一个记录的习惯,至少给正在变强路上的你留些沙雕记忆。最后祝愿大家生活愉快……

 

 


转载:https://blog.csdn.net/qq_41216743/article/details/105681668
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场