关键词

spring mvc 组合mybatis框架实例详解

Spring MVC 搭配 MyBatis 框架实例详解

本文将针对如何使用 Spring MVC 框架搭配 MyBatis 框架展开讲解,包括环境搭建、配置,以及搭建一个简单的增删改查示例。

环境搭建

为了使用 Spring MVC 搭配 MyBatis 框架,我们需要先完成以下环境的搭建:

  • JDK:需要 JDK 版本为 1.8 或以上;
  • Maven:使用 Maven 进行项目依赖和管理;
  • Spring MVC:使用 Spring MVC 作为 Web 框架,版本为 5.3.5;
  • MyBatis:使用 MyBatis 作为 ORM 框架,版本为 3.5.6;
  • MySQL:使用 MySQL 作为数据库,版本为 8.0.23。

配置文件

pom.xml

在 Maven 的 pom.xml 文件中加入以下依赖:

<!-- Spring MVC -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.5</version>
</dependency>

<!-- MyBatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.6</version>
</dependency>

<!-- MySQL Connector -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.23</version>
</dependency>

applicationContext.xml

在 Spring MVC 的 applicationContext.xml 文件中加入以下配置:

<!-- 数据库连接配置 -->
<bean id="dataSource" 
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC" />
    <property name="username" value="root" />
    <property name="password" value="123456" />
</bean>

<!-- MyBatis 配置,包括数据库连接和 mapper 配置 -->
<bean id="sqlSessionFactory" 
    class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="configLocation" value="classpath:mybatis-config.xml" />
    <property name="mapperLocations" value="classpath*:com/example/mapper/*.xml" />
</bean>

<!-- MyBatis Mapper 自动扫描 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.mapper" />
</bean>

<!-- 注册 Controller 类 -->
<context:component-scan base-package="com.example.controller" />

mybatis-config.xml

在 MyBatis 的 mybatis-config.xml 文件中加入以下配置:

<?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>
    <!-- 使用注解方式进行 Mapper 映射 -->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <setting name="logImpl" value="LOG4J2"/>
    </settings>

    <!-- Mapper 文件自动扫描 -->
    <mappers>
        <mapper class="com.example.mapper.UserMapper" />
    </mappers>
</configuration>

示例说明

以下是一个简单的示例,实现增删改查功能:

UserMapper.java

package com.example.mapper;

import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.example.dto.User;

public interface UserMapper {
    @Select("SELECT * FROM user")
    List<User> getUsers();

    @Select("SELECT * FROM user WHERE id = #{id}")
    User getUserById(int id);

    @Insert("INSERT INTO user (name, age) VALUES (#{name}, #{age})")
    void addUser(User user);

    @Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
    void updateUser(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    void deleteUser(int id);
}

UserController.java

package com.example.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.dto.User;
import com.example.mapper.UserMapper;

@Controller
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @GetMapping("/user/all")
    public String getUsers(ModelMap modelMap) {
        List<User> users = userMapper.getUsers();
        modelMap.addAttribute("users", users);
        return "user_list";
    }

    @GetMapping("/user/add")
    public String addUserView() {
        return "user_add";
    }

    @PostMapping("/user/add")
    public String addUser(User user) {
        userMapper.addUser(user);
        return "redirect:/user/all";
    }

    @GetMapping("/user/edit/{id}")
    public String editUserView(@PathVariable("id") int id, ModelMap modelMap) {
        User user = userMapper.getUserById(id);
        modelMap.addAttribute("user", user);
        return "user_edit";
    }

    @PostMapping("/user/edit")
    public String editUser(User user) {
        userMapper.updateUser(user);
        return "redirect:/user/all";
    }

    @GetMapping("/user/delete/{id}")
    public String deleteUser(@PathVariable("id") int id) {
        userMapper.deleteUser(id);
        return "redirect:/user/all";
    }
}

user_list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>User List</title>
</head>
<body>
    <h1>User List</h1>
    <a href="${pageContext.request.contextPath}/user/add">Add User</a>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th>Operation</th>  
        </tr>
        <c:forEach var="user" items="${users}">
            <tr>
                <td>${user.id}</td>
                <td>${user.name}</td>
                <td>${user.age}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/user/edit/${user.id}">Edit</a>
                    <a href="${pageContext.request.contextPath}/user/delete/${user.id}">Delete</a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

user_add.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Add User</title>
</head>
<body>
    <h1>Add User</h1>
    <form action="${pageContext.request.contextPath}/user/add" method="post">
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" /></td>
            </tr>
            <tr>
                <td>Age:</td>
                <td><input type="text" name="age" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Add" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

user_edit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>Edit User</title>
</head>
<body>
    <h1>Edit User</h1>
    <form action="${pageContext.request.contextPath}/user/edit" method="post">
        <table>
            <input type="hidden" name="id" value="${user.id}" />
            <tr>
                <td>Name:</td>
                <td><input type="text" name="name" value="${user.name}" /></td>
            </tr>
            <tr>
                <td>Age:</td>
                <td><input type="text" name="age" value="${user.age}" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Save" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

结束语

通过上述的配置和示例,你已经了解了如何使用 Spring MVC 搭配 MyBatis 框架。当然,这里只是简单的示例,实际生产环境中可能会更加复杂。但通过这个例子的理解,你应该理解了整个框架的基本原理。

本文链接:http://task.lmcjl.com/news/8149.html

展开阅读全文