SSM整合

一、环境准备

环境说明:

  • IDEA 2020.3
  • Mysql 8.0.21
  • Tomcat 9
  • Maven 3.6.3

要求:

  • 需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;

一、数据库搭建

创建一个存放书籍数据的数据库表:

  1. CREATE DATABASE `ssmbuild`;
  2. USE `ssmbuild`;
  3. DROP TABLE IF EXISTS `books`;
  4. CREATE TABLE `books` (
  5. `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
  6. `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
  7. `bookCounts` INT(11) NOT NULL COMMENT '数量',
  8. `detail` VARCHAR(200) NOT NULL COMMENT '描述',
  9. KEY `bookID` (`bookID`)
  10. ) ENGINE=INNODB DEFAULT CHARSET=utf8;
  11. INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
  12. (1,'Java',1,'从入门到放弃'),
  13. (2,'MySQL',10,'从删库到跑路'),
  14. (3,'Linux',5,'从进门到进牢');

二、基本环境搭建

1、新建一个Maven项目!SSM , 添加web的支持

2、导入相关的pom依赖!

  1. <dependencies>
  2. <dependency>
  3. <!--Junit-->
  4. <groupId>junit</groupId>
  5. <artifactId>junit</artifactId>
  6. <version>4.13</version>
  7. <scope>test</scope>
  8. </dependency>
  9. <!--数据库驱动-->
  10. <dependency>
  11. <groupId>mysql</groupId>
  12. <artifactId>mysql-connector-java</artifactId>
  13. <version>8.0.20</version>
  14. </dependency>
  15. <!-- 数据库连接池 -->
  16. <dependency>
  17. <groupId>com.mchange</groupId>
  18. <artifactId>c3p0</artifactId>
  19. <version>0.9.5.2</version>
  20. </dependency>
  21. <!--Servlet - JSP -->
  22. <dependency>
  23. <groupId>javax.servlet</groupId>
  24. <artifactId>servlet-api</artifactId>
  25. <version>2.5</version>
  26. </dependency>
  27. <dependency>
  28. <groupId>javax.servlet.jsp</groupId>
  29. <artifactId>jsp-api</artifactId>
  30. <version>2.2</version>
  31. </dependency>
  32. <dependency>
  33. <groupId>javax.servlet</groupId>
  34. <artifactId>jstl</artifactId>
  35. <version>1.2</version>
  36. </dependency>
  37. <!--Mybatis-->
  38. <dependency>
  39. <groupId>org.mybatis</groupId>
  40. <artifactId>mybatis</artifactId>
  41. <version>3.5.6</version>
  42. </dependency>
  43. <dependency>
  44. <groupId>org.mybatis</groupId>
  45. <artifactId>mybatis-spring</artifactId>
  46. <version>2.0.2</version>
  47. </dependency>
  48. <!--Spring-->
  49. <dependency>
  50. <groupId>org.springframework</groupId>
  51. <artifactId>spring-webmvc</artifactId>
  52. <version>5.2.9.RELEASE</version>
  53. </dependency>
  54. <dependency>
  55. <groupId>org.springframework</groupId>
  56. <artifactId>spring-jdbc</artifactId>
  57. <version>5.2.9.RELEASE</version>
  58. </dependency>
  59. <!-- lombok插件:懒人福音-->
  60. <dependency>
  61. <groupId>org.projectlombok</groupId>
  62. <artifactId>lombok</artifactId>
  63. <version>1.18.16</version>
  64. </dependency>
  65. </dependencies>

3、Maven资源过滤设置

  1. <build>
  2. <resources>
  3. <resource>
  4. <directory>src/main/java</directory>
  5. <includes>
  6. <include>**/*.properties</include>
  7. <include>**/*.xml</include>
  8. </includes>
  9. <filtering>false</filtering>
  10. </resource>
  11. <resource>
  12. <directory>src/main/resources</directory>
  13. <includes>
  14. <include>**/*.properties</include>
  15. <include>**/*.xml</include>
  16. </includes>
  17. <filtering>false</filtering>
  18. </resource>
  19. </resources>
  20. </build>

4、建立基本结构和配置框架!

项目结构如下:

SSM整合 - 图1

  • com.chen66.pojo
  • com.chen66.dao
  • com.chen66.service
  • com.chen66.controller
  • mybatis-config.xml ```xml <?xml version=”1.0” encoding=”UTF-8” ?> <!DOCTYPE configuration
    1. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">

  1. - application-config.xml
  2. ```xml
  3. <?xml version="1.0" encoding="UTF-8"?>
  4. <beans xmlns="http://www.springframework.org/schema/beans"
  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. </beans>

二、Mybatis层

1、数据库配置文件 db.properties

  1. driver=com.mysql.cj.jdbc.Driver
  2. url=jdbc:mysql://localhost:3306/ssmbuild?serverTimezone=Asia/Shanghai&useSSL=true&useUnicode=true&characterEncoding=UTF-8
  3. username=root
  4. password=root

2、IDEA关联数据库

3、编写MyBatis的核心配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <typeAliases>
  7. <package name="com.chen66.pojo"/>
  8. </typeAliases>
  9. <mappers>
  10. <mapper resource="com/chen66/dao/BookMapper.xml"/>
  11. </mappers>
  12. </configuration>

4、编写数据库对应的实体类 com.chen66.pojo.Books

Books.java

使用lombok插件!

  1. package com.chen66.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @AllArgsConstructor
  7. @NoArgsConstructor
  8. public class Books {
  9. private int bookID;
  10. private String bookName;
  11. private int bookCounts;
  12. private String detail;
  13. }

5、编写Dao层的 Mapper接口!

  1. public interface BookMapper {
  2. //增加书籍
  3. int addBook(Books books);
  4. //删除书籍,通过Id删除
  5. int deleteBook(@Param("BookId") int id);
  6. //修改书籍
  7. int updateBook(Books books);
  8. //查找书籍
  9. //通过Id查找
  10. Books queryBookById(@Param("BookId") int id);
  11. //查找所有书籍
  12. List<Books> queryAllBooks();
  13. }

6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.chen66.dao.BookMapper">
  6. <!-- 增加书籍-->
  7. <insert id="addBook" parameterType="Books">
  8. insert into books(bookId,bookName,bookCounts,detail) values(#{bookId},#{bookName},#{bookCounts},#{detail})
  9. </insert>
  10. <!-- 删除书籍,通过Id删除-->
  11. <delete id="deleteBook" parameterType="_int">
  12. delete from books where bookID=#{BookId}
  13. </delete>
  14. <!-- 修改书籍-->
  15. <update id="updateBook" parameterType="Books">
  16. update books
  17. set bookName=#{bookName},bookCounts=#{bookCounts},detail=#{detail}
  18. where bookId=#{bookId}
  19. </update>
  20. <!-- 通过Id查找-->
  21. <select id="queryBookById" resultType="Books">
  22. select *from ssmbuild.books where bookID=#{BookId}
  23. </select>
  24. <!-- 查找所有书籍-->
  25. <select id="queryAllBooks" resultType="Books">
  26. select *from books
  27. </select>
  28. </mapper>

7、编写Service层的接口和实现类

  1. package com.chen66.service;
  2. import com.chen66.dao.BookMapper;
  3. import com.chen66.pojo.Books;
  4. import java.util.List;
  5. public class BookServiceImpl implements BookService{
  6. //调用dao层的操作,设置一个set接口,方便Spring管理
  7. private BookMapper bookMapper;
  8. public void setBookMapper(BookMapper bookMapper) {
  9. this.bookMapper = bookMapper;
  10. }
  11. @Override
  12. public int addBook(Books books) {
  13. return bookMapper.addBook(books);
  14. }
  15. @Override
  16. public int deleteBook(int id) {
  17. return bookMapper.deleteBook(id);
  18. }
  19. @Override
  20. public int updateBook(Books books) {
  21. return bookMapper.updateBook(books);
  22. }
  23. @Override
  24. public Books queryBookById(int id) {
  25. return bookMapper.queryBookById(id);
  26. }
  27. @Override
  28. public List<Books> queryAllBooks() {
  29. return bookMapper.queryAllBooks();
  30. }
  31. }

三、Spring层

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

2、我们去编写Spring整合Mybatis的相关的配置文件;

spring-dao.xml

  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. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. https://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 配置整合mybatis -->
  10. <!-- 1.关联数据库文件 -->
  11. <context:property-placeholder location="classpath:db.properties"/>
  12. <!-- 2.数据库连接池 -->
  13. <!--数据库连接池
  14. dbcp 半自动化操作 不能自动连接
  15. c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
  16. -->
  17. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  18. <!-- 配置连接池属性 -->
  19. <property name="driverClass" value="${jdbc.driver}"/>
  20. <property name="jdbcUrl" value="${jdbc.url}"/>
  21. <property name="user" value="${jdbc.username}"/>
  22. <property name="password" value="${jdbc.password}"/>
  23. <!-- c3p0连接池的私有属性 -->
  24. <property name="maxPoolSize" value="30"/>
  25. <property name="minPoolSize" value="10"/>
  26. <!-- 关闭连接后不自动commit -->
  27. <property name="autoCommitOnClose" value="false"/>
  28. <!-- 获取连接超时时间 -->
  29. <property name="checkoutTimeout" value="10000"/>
  30. <!-- 当获取连接失败重试次数 -->
  31. <property name="acquireRetryAttempts" value="2"/>
  32. </bean>
  33. <!-- 3.配置SqlSessionFactory对象 -->
  34. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  35. <!-- 注入数据库连接池 -->
  36. <property name="dataSource" ref="dataSource"/>
  37. <!-- 配置Mybatis全局配置文件:mybatis-config.xml -->
  38. <property name="configLocation" value="classpath:mybatis-config.xml"/>
  39. </bean>
  40. <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
  41. <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
  42. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  43. <!-- 注入sqlSessionFactory -->
  44. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  45. <!-- 给出需要扫描Dao接口包 -->
  46. <property name="basePackage" value="com.chen66.dao"/>
  47. </bean>
  48. </beans>

3、Spring整合service层

新建一个资源文件spring-service.xml

  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. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 扫描service相关的bean -->
  10. <context:component-scan base-package="com.chen66.service" />
  11. <!--BookServiceImpl注入到IOC容器中-->
  12. <bean id="BookServiceImpl" class="com.chen66.service.BookServiceImpl">
  13. <property name="bookMapper" ref="bookMapper"/>
  14. </bean>
  15. <!-- 配置事务管理器 -->
  16. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  17. <!-- 注入数据库连接池 -->
  18. <property name="dataSource" ref="dataSource" />
  19. </bean>
  20. </beans>

四、SpringMVC层

1.web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <servlet>
  7. <servlet-name>springmvc</servlet-name>
  8. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  9. <init-param>
  10. <param-name>contextConfigLocation</param-name>
  11. <param-value>classpath:applicationContext.xml</param-value>
  12. <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
  13. </init-param>
  14. <load-on-startup>1</load-on-startup>
  15. </servlet>
  16. <servlet-mapping>
  17. <servlet-name>springmvc</servlet-name>
  18. <url-pattern>/</url-pattern>
  19. </servlet-mapping>
  20. <!--encodingFilter-->
  21. <filter>
  22. <filter-name>encodingFilter</filter-name>
  23. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  24. <init-param>
  25. <param-name>encoding</param-name>
  26. <param-value>utf-8</param-value>
  27. </init-param>
  28. </filter>
  29. <filter-mapping>
  30. <filter-name>encodingFilter</filter-name>
  31. <url-pattern>/*</url-pattern>
  32. </filter-mapping>
  33. <!-- Session过期时间-->
  34. <session-config>
  35. <session-timeout>15</session-timeout>
  36. </session-config>
  37. </web-app>

2.spring-mvc.xml

  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:mvc="http://www.springframework.org/schema/mvc"
  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/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/mvc
  11. https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  12. <!-- 配置SpringMVC -->
  13. <!-- 1.开启SpringMVC注解驱动 -->
  14. <mvc:annotation-driven/>
  15. <!-- 2.静态资源默认servlet配置-->
  16. <mvc:default-servlet-handler/>
  17. <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
  18. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  20. <property name="prefix" value="/WEB-INF/jsp/"/>
  21. <property name="suffix" value=".jsp"/>
  22. </bean>
  23. <!-- 4.扫描web相关的bean -->
  24. <context:component-scan base-package="com.chen66.controller" />
  25. </beans>

3、Spring配置整合文件,applicationContext.xml

  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. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <import resource="spring-dao.xml"/>
  7. <import resource="spring-service.xml"/>
  8. <import resource="spring-mvc.xml"/>
  9. </beans>