SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

靠譜楊 發表於 2021-11-28
框架 MyBatis Spring

整合SSM

SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】


01 基本配置檔案的關係

SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

web.xml配置DispatcherServlet

SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】


02 需要的maven依賴

<!--依賴
1、junit
2、資料庫連線池
3、servlet
4、jsp
5、mybatis
6、mybatis-spring
7、spring
-->
<dependencies>
    <!--log4j-->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <!--lombok外掛-->
    <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.10</version>
    </dependency>
    <!--Junit-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <!--資料庫驅動-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- 資料庫連線池 -->
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.5.2</version>
    </dependency>
    <!--Servlet - JSP -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!--Mybatis-->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.2</version>
    </dependency>
    <!--Spring-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
</dependencies>
<!--資源過濾-->
<build>
    <resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

一、spring整合mybatis配置

01 mybatis核心配置檔案mybatis-config.xml

  • 起別名
  • 新增mapper對映
  • 新增setting
<?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.kuang.pojo"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/kuang/dao/BookMapper.xml"/>
    </mappers>
</configuration>

02 spring整合配置檔案spring-dao.xml

  • 關聯資料庫配置資訊,配置連線池
  • 配置SqlSessionFactory物件
  • 配置掃描Dao介面包,動態實現Dao介面注入到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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置整合mybatis -->
    <!-- 1.關聯資料庫檔案 -->
    <context:property-placeholder location="classpath:database.properties"/>
    <!-- 2.資料庫連線池 -->
    <!--資料庫連線池
        dbcp  半自動化操作  不能自動連線
        c3p0  自動化操作(自動的載入配置檔案 並且設定到物件裡面)
    -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置連線池屬性 -->
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!-- c3p0連線池的私有屬性 -->
        <property name="maxPoolSize" value="30"/>
        <property name="minPoolSize" value="10"/>
        <!-- 關閉連線後不自動commit -->
        <property name="autoCommitOnClose" value="false"/>
        <!-- 獲取連線超時時間 -->
        <property name="checkoutTimeout" value="10000"/>
        <!-- 當獲取連線失敗重試次數 -->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!-- 3.配置SqlSessionFactory物件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入資料庫連線池 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置MyBaties全域性配置檔案:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

    <!-- 4.配置掃描Dao介面包,動態實現Dao介面注入到spring容器中 -->
    <!--解釋 : https://www.cnblogs.com/jpfss/p/7799806.html-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 給出需要掃描Dao介面包 -->
        <property name="basePackage" value="com.kuang.dao"/>
    </bean>
</beans>
  • 到這裡dao層的資料獲取部分已經配置完成,其中獲取sqlSession的方式有所不同,之前有兩種方式獲取sqlSession物件:
  1. 利用構造器注入
package com.kuang.dao;

import com.kuang.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserMapperImpl implements  UserMapper {
	//sqlSession不用我們自己建立了,Spring來管理
	private SqlSessionTemplate sqlSession;
	public void setSqlSession(SqlSessionTemplate sqlSession) {
		this.sqlSession = sqlSession;
	}
	public List<User> selectUser() {
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		return mapper.selectUser();
	}
}

<import resource="spring-dao.xml"></import>
 <!---->
 <bean id="userMapper" class="com.kuang.dao.UserMapperImpl">
     <property name="sqlSession" ref="sqlSession"></property>
 </bean>
<!--註冊sqlSessionTemplate , 關聯sqlSessionFactory-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--利用構造器注入-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
  1. 繼承SqlSessionDaoSupport,直接使用getSqlSession().getMapper(UserMapper.class);獲取

    引用spring-dao.xml的sqlSessionFactory,代理生成sqlSession物件

<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--關聯Mybatis-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/kuang/dao/*.xml"/>
</bean>
package com.kuang.dao;

import com.kuang.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper  {
	public List<User> selectUser() {
		UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
		return mapper.selectUser();
	}
}

<bean id="userMapper2" class="com.kuang.dao.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
  • 現在配置的方法是最簡單的,不需要再手動獲取sqlSession物件,由Spring動態生成並執行sql語句!

二、spring-mybatis-springmvc

SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】

01 springmvc主要管理的是controller層和service層

  • controller層主要負責決定要從dao層獲取什麼資料,還有這些資料要渲染到什麼檢視上。
  • service層主要負責實現dao層的方法,定義一個新介面,這個介面裡的方法來自dao層介面的方法,然後寫一個Impl實現這個介面。

spring-mvc.xml整合controller層

  • 開啟註解支援
  • 預設過濾靜態資源
  • 配置ViewResolver檢視解析器
  • 掃描controller層的bean完成注入
<?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:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="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.xsd
    http://www.springframework.org/schema/mvc
    https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!-- 配置SpringMVC -->
    <!-- 1.開啟SpringMVC註解驅動 -->
    <mvc:annotation-driven />
    <!-- 2.靜態資源預設servlet配置-->
    <mvc:default-servlet-handler/>
    <!-- 3.配置jsp 顯示ViewResolver檢視解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <!-- 4.掃描web相關的bean -->
    <context:component-scan base-package="com.kuang.controller"/>
</beans>

spring-service.xml整合service層

  • 掃描service層的bean完成注入
  • 把Impl實現方法注入到IOC容器,主要是給引數private BookMapper bookMapper 賦值
  • 配置事務管理器
<?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"
       xsi:schemaLocation="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.xsd">
    <!-- 掃描service相關的bean -->
    <context:component-scan base-package="com.kuang.service" />
    <!--BookServiceImpl注入到IOC容器中-->
    <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>
    <!-- 配置事務管理器 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入資料庫連線池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>
</beans>

三、Spring配置整合檔案,applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <import resource="spring-dao.xml"/>
    <import resource="spring-service.xml"/>
    <import resource="spring-mvc.xml"/>
</beans>

四、補充service層的實現方法

package com.kuang.service;
import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;
import java.util.List;

public class BookServiceImpl implements BookService {
   //呼叫dao層的操作,設定一個set介面,方便Spring管理
   private BookMapper bookMapper;
   public void setBookMapper(BookMapper bookMapper) {
      this.bookMapper = bookMapper;
   }
   public int addBook(Books book) {
      return bookMapper.addBook(book);
   }
   public int deleteBookById(int id) {
      return bookMapper.deleteBookById(id);
   }
   public int updateBook(Books books) {
      return bookMapper.updateBook(books);
   }
   public Books queryBookById(int id) {
      return bookMapper.queryBookById(id);
   }
   public List<Books> queryAllBook() {
      return bookMapper.queryAllBook();
   }
}
  • //呼叫dao層的操作,設定一個set介面,方便Spring管理
    private BookMapper bookMapper;

在spring-service.xml中的

<!--BookServiceImpl注入到IOC容器中 主要是給引數private BookMapper bookMapper;賦值-->
<bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
    <property name="bookMapper" ref="bookMapper"/>
</bean>

五、補充controller層的方法

package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {
   @Autowired
   @Qualifier("BookServiceImpl")
   private BookService bookService;
   @RequestMapping("/allBook")
   public String list(Model model) {
      List<Books> list = bookService.queryAllBook();
      model.addAttribute("list", list);
      return "allBook";
   }

   @RequestMapping("/toAddBook")
   public String toAddPaper() {
      return "addBook";
   }
   @RequestMapping("/addBook")
   public String addPaper(Books books) {
      System.out.println(books);
      bookService.addBook(books);
      return "redirect:/book/allBook";
   }

   @RequestMapping("/toUpdateBook")
   public String toUpdateBook(Model model, int id) {
      Books books = bookService.queryBookById(id);
      System.out.println(books);
      model.addAttribute("book",books );
      return "updateBook";
   }
   @RequestMapping("/updateBook")
   public String updateBook(Model model, Books book) {
      System.out.println(book);
      bookService.updateBook(book);
      Books books = bookService.queryBookById(book.getBookID());
      model.addAttribute("books", books);
      return "redirect:/book/allBook";
   }

   @RequestMapping("/del/{bookId}")
   public String deleteBook(@PathVariable("bookId") int id) {
      bookService.deleteBookById(id);
      return "redirect:/book/allBook";
   }
}

六、總結

  • mybatis-config.xml 完成dao層的mapper和mapper.xml的對映(掃描這個包並配置mapper)
  • spring-dao.xml 幫助mybatis整合到spring中,主要完成獲取資料庫連線以及獲取sqlSession物件並完成dao層mapper的自動注入。
  • spring-mvc.xml 完成controller層的配置,掃描controller層的bean掃描,完成檢視解析。
  • spring-service.xml 把service層的方法注入到IOC容器中,完成配置事務管理。
  • web.xml 完成DispatcherServlet的配置以及字元編碼過濾(UTF-8)。
  • applicationContext.xml 完成所有配置檔案的整合引入。