SpringMVC 是一個基于 Java 的實現(xiàn)了 MVC 設(shè)計模式的請求驅(qū)動類型的輕量級 Web 框架,而 MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。將 SpringMVC 和 MyBatis 進行整合,可以充分發(fā)揮兩者的優(yōu)勢,實現(xiàn)高效的 Web 應用開發(fā)。下面將詳細介紹 SpringMVC 整合 MyBatis 的具體步驟。
步驟一:創(chuàng)建 Maven 項目
首先,我們需要創(chuàng)建一個 Maven 項目,這樣可以方便地管理項目的依賴。在 IDE 中創(chuàng)建一個新的 Maven 項目,選擇合適的項目路徑和命名。創(chuàng)建完成后,在項目的 pom.xml 文件中添加所需的依賴。以下是一個示例的 pom.xml 文件內(nèi)容:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>springmvc-mybatis-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.18</version>
</dependency>
<!-- MyBatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- MyBatis-Spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
<!-- JDBC 驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- 數(shù)據(jù)庫連接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.8</version>
</dependency>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>上述依賴中包含了 SpringMVC、MyBatis、MyBatis-Spring、MySQL 驅(qū)動、Druid 數(shù)據(jù)庫連接池以及 Servlet API。添加完依賴后,Maven 會自動下載這些依賴到項目中。
步驟二:配置 SpringMVC
接下來,我們需要配置 SpringMVC。在 src/main/resources 目錄下創(chuàng)建 springmvc-servlet.xml 文件,用于配置 SpringMVC 的相關(guān)信息。以下是一個示例的配置文件內(nèi)容:
<?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
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 開啟組件掃描 -->
<context:component-scan base-package="com.example.controller"/>
<!-- 開啟 SpringMVC 注解支持 -->
<mvc:annotation-driven/>
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>在上述配置中,我們使用 <context:component-scan> 標簽開啟了組件掃描,指定了掃描的包路徑為 com.example.controller,這樣 SpringMVC 會自動掃描該包下的控制器類。<mvc:annotation-driven> 標簽用于開啟 SpringMVC 的注解支持。InternalResourceViewResolver 是一個視圖解析器,用于解析視圖的路徑,這里將視圖文件放在 /WEB-INF/views/ 目錄下,并且以 .jsp 為后綴。
然后,在 web.xml 文件中配置 SpringMVC 的前端控制器 DispatcherServlet。以下是一個示例的 web.xml 文件內(nèi)容:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!-- 配置 SpringMVC 的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>在上述配置中,我們配置了 DispatcherServlet,并指定了其配置文件的位置為 classpath:springmvc-servlet.xml。<load-on-startup>1</load-on-startup> 表示在服務器啟動時就加載該 Servlet。<url-pattern>/</url-pattern> 表示將所有的請求都交給 DispatcherServlet 處理。
步驟三:配置 MyBatis 和數(shù)據(jù)源
在 src/main/resources 目錄下創(chuàng)建 applicationContext.xml 文件,用于配置 MyBatis 和數(shù)據(jù)源。以下是一個示例的配置文件內(nèi)容:
<?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">
<!-- 加載屬性文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!-- 配置數(shù)據(jù)源 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
</bean>
<!-- 配置 SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>
<!-- 配置 MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
</beans>在上述配置中,我們首先使用 <context:property-placeholder> 標簽加載了 jdbc.properties 文件,該文件用于存儲數(shù)據(jù)庫的連接信息。以下是一個示例的 jdbc.properties 文件內(nèi)容:
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC jdbc.username=root jdbc.password=123456 jdbc.driver=com.mysql.cj.jdbc.Driver
然后,我們配置了 Druid 數(shù)據(jù)源,將數(shù)據(jù)庫的連接信息注入到數(shù)據(jù)源中。接著,配置了 SqlSessionFactoryBean,指定了數(shù)據(jù)源和 Mapper XML 文件的位置。最后,使用 MapperScannerConfigurer 掃描指定包下的 Mapper 接口,將其注冊為 Spring Bean。
步驟四:創(chuàng)建實體類和 Mapper 接口
在 com.example.entity 包下創(chuàng)建實體類,用于映射數(shù)據(jù)庫表。例如,創(chuàng)建一個 User 實體類:
package com.example.entity;
public class User {
private Integer id;
private String username;
private String password;
// 省略 getter 和 setter 方法
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}在 com.example.mapper 包下創(chuàng)建 Mapper 接口,用于定義數(shù)據(jù)庫操作方法。例如,創(chuàng)建一個 UserMapper 接口:
package com.example.mapper;
import com.example.entity.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
}在 src/main/resources/mapper 目錄下創(chuàng)建對應的 Mapper XML 文件,實現(xiàn) Mapper 接口中的方法。例如,創(chuàng)建 UserMapper.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">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findAll" resultType="com.example.entity.User">
SELECT * FROM user
</select>
</mapper>步驟五:創(chuàng)建 Service 層和 Controller 層
在 com.example.service 包下創(chuàng)建 Service 接口和實現(xiàn)類,用于處理業(yè)務邏輯。例如,創(chuàng)建 UserService 接口和 UserServiceImpl 實現(xiàn)類:
package com.example.service;
import com.example.entity.User;
import java.util.List;
public interface UserService {
List<User> findAll();
}
package com.example.service.impl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public List<User> findAll() {
return userMapper.findAll();
}
}在 com.example.controller 包下創(chuàng)建 Controller 類,用于處理請求和返回響應。例如,創(chuàng)建 UserController 類:
package com.example.controller;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/list")
public String list(Model model) {
List<User> userList = userService.findAll();
model.addAttribute("userList", userList);
return "userList";
}
}步驟六:創(chuàng)建視圖文件
在 /WEB-INF/views/ 目錄下創(chuàng)建 userList.jsp 文件,用于顯示用戶列表。以下是一個示例的 userList.jsp 文件內(nèi)容:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用戶列表</title>
</head>
<body>
<h1>用戶列表</h1>
<table border="1">
<tr>
<th>ID</th>
<th>用戶名</th>
<th>密碼</th>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
</table>
</body>
</html>在上述 JSP 文件中,我們使用了 JSTL 的 <c:forEach> 標簽來遍歷用戶列表,并將用戶信息顯示在表格中。