SpringBoot-Mybatis整合

发布时间 2024-01-10 17:48:35作者: 菜鸡前来

 

  1. 创建数据库

    CREATE TABLE `user` (
      `id` int(11) NOT NULL AUTO_INCREMENT comment '学号',
      `name` varchar(20) DEFAULT NULL,
      `pwd` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
  2. 创建一个spring boot项目

  3. 添加依赖在pom.xml文件中

    <?xml version="1.0" encoding="UTF-8"?>
    <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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>3.2.1</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.lyh</groupId>
        <artifactId>springBoot-mybatis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springBoot-mybatis</name>
        <description>springBoot-mybatis</description>
        <properties>
            <java.version>17</java.version>
        </properties>
        <dependencies>
    ​
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--        添加mybatis依赖-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>3.0.3</version>
            </dependency>
            <!--        添加数据库驱动依赖-->
            <dependency>
                <groupId>com.mysql</groupId>
                <artifactId>mysql-connector-j</artifactId>
                <scope>runtime</scope>
            </dependency>
            <!--        lombok依赖,不用写有参无参构造了-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.15</version>
            </dependency>
            <!-- pagehelper 分页插件-->
            <dependency>
                <groupId>com.github.pagehelper</groupId>
                <artifactId>pagehelper-spring-boot-starter</artifactId>
                <version>1.2.12</version>
            </dependency>
    <!--        页面跳转依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    <!--        热部署-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-devtools</artifactId>
                <scope>runtime</scope>
                <optional>true</optional>
            </dependency>
    <!--        测试-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
    ​
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    ​
    </project>
  4. 编写application.yml文件

    server:
      port: 8080
    ​
    #??????
    spring:
      datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        username: root
        password: 123456
        url: jdbc:mysql://localhost:3306/chlmxt?useSSL=true&useUnicode=true&characterEncoding=utf8
        driver-class-name: com.mysql.cj.jdbc.Driver
    mybatis:
      type-aliases-package: com.lyh.springbootmybatis.pojo   
      mapper-locations: classpath:/mybatis/*.xml      
  5. 编写mbatis配置文件(UserMapper.xml)

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.lyh.springbootmybatis.dao.UserDao">
        <select id="listUser" parameterType="com.lyh.springbootmybatis.pojo.User">
            SELECT * FROM chlmxt.`user`;
        </select>
    <!--    根据ID查询用户-->
        <select id="queryById" parameterType="com.lyh.springbootmybatis.pojo.User">
            select * from chlmxt.`user` where id=#{id}
        </select>
        <select id="listUserByName" parameterType="com.lyh.springbootmybatis.pojo.User">
            select *from chlmxt.`user`
    <where>
        <if test="name !=null and name !=''">
            and `name` like concat('%',#{name},'%')
        </if>
    </where>
        </select>
    <!--    根据id删除-->
        <delete id="deleteUserById" parameterType="int">
            delete from chlmxt.`user` where id=#{id}
        </delete>
    <!--    修改数据-->
        <update id="updateUser" parameterType="com.lyh.springbootmybatis.pojo.User">
            update chlmxt.`user` set name = #{name},pwd = #{pwd} where id = #{id}
        </update>
    <!--    添加用户-->
        <insert id="addUser" parameterType="com.lyh.springbootmybatis.pojo.User">
            insert into chlmxt.user(name,pwd) values (#{name},#{pwd})
        </insert>
    </mapper>
  6. 编写实体类

    package com.lyh.springbootmybatis.pojo;
    ​
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    ​
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
        private Integer id;
        private String name;
        private String pwd;
    }
  7. 编写分页查询的类

    package com.lyh.springbootmybatis.pojo.query;
    ​
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    ​
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class UserQuery {
        //当前页
        private Integer pageNum =1;
        //每页显示的数量
        private Integer pageSize =2;
        //根据用户名查询
        private String name;
    }
  8. 编写dao层

    package com.lyh.springbootmybatis.dao;
    ​
    import com.github.pagehelper.PageInfo;
    import com.lyh.springbootmybatis.pojo.User;
    import com.lyh.springbootmybatis.pojo.query.UserQuery;
    import org.apache.ibatis.annotations.Mapper;
    import org.springframework.stereotype.Repository;
    ​
    import java.util.List;
    ​
    //Mapper:告诉springboot这是一个mybatis的mapper类
    //Repository:把UserDao交给spring容器管理
    @Mapper
    @Repository
    public interface UserDao {
        //查询所以用户
        public List<User> listUser();
        //根据ID查询用户
        public User queryById(Integer id);
        //根据用户名查询用户  并分页
        public List<User> listUserByName(UserQuery userQuery);
        //根据ID删除用户
        public int deleteUserById(Integer id);
        //修改用户
        public int updateUser(User user);
        //添加用户
        public int addUser(User user);
    }
  9. 记住在dao层中写一个功能需要去对应的Mapper.xml相应的去配置写一个功能

  10. 编写service

    package com.lyh.springbootmybatis.service;
    ​
    import com.github.pagehelper.PageInfo;
    import com.lyh.springbootmybatis.pojo.User;
    import com.lyh.springbootmybatis.pojo.query.UserQuery;
    ​
    import java.util.List;
    ​
    public interface UserService {
        //查询所以用户
        public List<User> listUser();
        //根据ID查询用户
        public User queryById(Integer id);
        //根据用户名查询用户  并分页
        public PageInfo<User> listUserByName(UserQuery userQuery);
        //根据ID删除用户
        public boolean deleteUserById(Integer id);
        //修改用户
        public boolean updateUser(User user);
        //添加用户
        public boolean addUser(User user);
    }
  11. 编写service实现类

    package com.lyh.springbootmybatis.service;
    ​
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.lyh.springbootmybatis.dao.UserDao;
    import com.lyh.springbootmybatis.pojo.User;
    import com.lyh.springbootmybatis.pojo.query.UserQuery;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    ​
    import java.util.List;
    //交由spring容器管理
    @Service
    public class UserServiceImpl implements UserService{
        @Autowired
        private UserDao userDao;
    ​
        @Override
        public List<User> listUser() {
            return userDao.listUser();
        }
    ​
        @Override
        public User queryById(Integer id) {
            return userDao.queryById(id);
        }
    ​
        @Override
        public PageInfo<User> listUserByName(UserQuery userQuery) {
            PageHelper.startPage(userQuery.getPageNum(),userQuery.getPageSize());
            return new PageInfo<>(userDao.listUserByName(userQuery));
        }
    ​
        @Override
        public boolean deleteUserById(Integer id) {
            int i = userDao.deleteUserById(id);
            if (i>0){
                return true;
            }else {
                return false;
            }
        }
    ​
        @Override
        public boolean updateUser(User user) {
            int i = userDao.updateUser(user);
            if (i>0){
                return true;
            }else {
                return false;
            }
        }
    ​
        @Override
        public boolean addUser(User user) {
            int i = userDao.addUser(user);
            if (i>0){
                return true;
            }else {
                return false;
            }
        }
    }
  12. 编写Controller层

    package com.lyh.springbootmybatis.controller;
    
    import com.github.pagehelper.PageInfo;
    import com.lyh.springbootmybatis.pojo.User;
    import com.lyh.springbootmybatis.pojo.query.UserQuery;
    import com.lyh.springbootmybatis.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.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;
    
    @Controller
    public class UserController {
        @Autowired
        private UserService userService;
    
        @GetMapping("/")
        public String index(Model model, UserQuery userQuery) {
            PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
            model.addAttribute("page", userPageInfo);
            return "index";
        }
    
        //根据ID查询用户
        @GetMapping("/edit/{id}")
        public String toEdit(@PathVariable("id") Integer id, Model model) {
            model.addAttribute("user", userService.queryById(id));
            return "editUser";
        }
    
        //当表单提交的时候才会执行
        @PostMapping("/")
        public String listUserByName(Model model, UserQuery userQuery) {
            PageInfo<User> userPageInfo = userService.listUserByName(userQuery);
            model.addAttribute("page", userPageInfo);
            return "index";
        }
    
        @GetMapping("/delete/{id}")
        public String delectUserById(@PathVariable("id") Integer id, RedirectAttributes attr) {
            boolean b = userService.deleteUserById(id);
            if (b) {
                attr.addAttribute("message", "删除成功");
                //如果删除成功,重定向到首页
                return "redirect:/";
            } else {
                attr.addAttribute("message", "删除失败");
                return "redirect:/";
            }
        }
    
        @PostMapping("/edit")
        public String edit(User user, RedirectAttributes attributes) {
            Integer id = user.getId();
            if (id == null) {
                boolean b = userService.addUser(user);
                if (b) {
                    attributes.addAttribute("message", "新增成功");
                    //如果删除成功,重定向到首页
                    return "redirect:/";
                } else {
                    attributes.addAttribute("message", "新增失败");
                    return "redirect:/";
                }
            } else {
                boolean b = userService.updateUser(user);
                if (b) {
                    attributes.addAttribute("message", "更新成功");
                    //如果删除成功,重定向到首页
                    return "redirect:/";
                } else {
                    attributes.addAttribute("message", "更新失败");
                    return "redirect:/";
                }
            }
    
        }
    
        @GetMapping("/addUser")
        public String addUser(Model model) {
            User user = new User();
            model.addAttribute("user", user);
            return "editUser";
        }
    }
  13. 页面测试

    1. 主页面

      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>首页</title>
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.5.0/dist/semantic.min.css">
      </head>
      <body>
      <div class="ui container">
          <div>
              <form th:action="@{/}" method="post">
                  <input type="text" name="name" placeholder="输入用户名">
                  <input type="submit" value="搜索" class="inverted circular search link icon">
              </form>
          </div>
      </div>
      
      <div class="ui container">
          <table class="ui celled table">
              <thead>
              <tr>
                  <th>id</th>
                  <th>姓名</th>
                  <th>密码</th>
                  <th>操作</th>
              </tr>
              </thead>
              <tbody>
              <tr th:each="user : ${page.list}">
                  <td th:text="${user.id}">James</td>
                  <td th:text="${user.name}">24</td>
                  <td th:text="${user.pwd}">Engineer</td>
                  <td>
                      <a th:href="@{/edit/{id}(id=${user.id})}" class="ui button mini teal">编辑</a>
                      <a th:href="@{/delete/{id}(id=${user.id})}" class="ui button mini teal">删除</a>
                      <a th:href="@{/addUser}" class="ui button mini teal">新增</a>
                  </td>
              </tr>
              </tbody>
          </table>
      </div>
      <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.5.0/dist/semantic.min.js"></script>
      </body>
      </html>
    2. 添加,修改页面

      <!DOCTYPE html>
      <html lang="en" xmlns:th="http://www.thymeleaf.org">
      <head>
          <meta charset="UTF-8">
          <title>Title</title>
          <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.5.0/dist/semantic.min.css">
      </head>
      <body>
      <div class="ui container">
          <form class="ui form" th:action="@{/edit}" method="post" th:object="${user}">
              <input type="hidden" th:value="*{id}" name="id">
              <div class="field">
                  <label>用户名</label>
      <!--            这里面的name和实体类里面的对应-->
                  <input type="text" name="name" placeholder="请输入用户名" required th:value="*{name}">
              </div>
              <div class="field">
                  <label>密码</label>
                  <input type="text" name="pwd" placeholder="请输入密码" required th:value="*{pwd}">
              </div>
              <button class="ui button" type="submit">Submit</button>
          </form>
      </div>
      </body>
      <script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.5.0/dist/semantic.min.js"></script>
      </html>
  14. 启动运行,完成撒花

  15.