SpringBoot整合Mybatis對單表的增、刪、改、查操作

来源:https://www.cnblogs.com/south-wood/archive/2020/03/07/12436978.html
-Advertisement-
Play Games

一.目標 SpringBoot整合Mybatis對單表的增、刪、改、查操作 二.開發工具及項目環境 IDE: IntelliJ IDEA 2019.3 SQL: Navicat for MySQL 三.基礎環境配置 1. 創建資料庫: demodb 2. 創建數據表及插入數據 3. 必備Maven依 ...


一.目標

SpringBoot整合Mybatis對單表的增、刪、改、查操作


二.開發工具及項目環境

  • IDE: IntelliJ IDEA 2019.3

  • SQL:Navicat for MySQL


三.基礎環境配置

  1. 創建資料庫:demodb

  2. 創建數據表及插入數據

    DROP TABLE IF EXISTS t_employee;
    CREATE TABLE t_employee (
      id int PRIMARY KEY AUTO_INCREMENT COMMENT '主鍵編號',
      name varchar(50) DEFAULT NULL COMMENT '員工姓名',
      sex varchar(2) DEFAULT NULL COMMENT '員工性別',
      phone varchar(11) DEFAULT NULL COMMENT '電話號碼'
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    
    INSERT INTO t_employee VALUES ('1', '張三豐', '男', '13812345678');
    INSERT INTO t_employee VALUES ('2', '郭靖', '男', '18898765432');
    INSERT INTO t_employee VALUES ('3', '小龍女', '女', '13965432188');
    INSERT INTO t_employee VALUES ('4', '趙敏', '女', '15896385278');
    
  3. 必備Maven依賴如下:

    <!--        MySQL依賴-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
                <version>5.1.48</version>
            </dependency>
    
    <!--        Thymleaf依賴-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
    
    <!--        mybatis依賴-->
       <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.1</version>
            </dependency>
  4. 添加配置文件,可用使用yaml配置,即application.yml(與application.properties配置文件,沒什麼太大的區別)連接池的配置如下:

    spring:
      ##連接資料庫配置
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        ##jdbc:mysql://(ip地址):(埠號)/(資料庫名)?useSSL=false
        url: jdbc:mysql://localhost:3306/demodb?useUnicode=true&useSSL=false&characterEncoding=UTF8
        ##資料庫登錄名
        data-username: root
        ##登陸密碼
        data-password:
    
      ##靜態資源的路徑
      resources:
        static-locations=classpath:/templates/
    
  5. 測試配置情況

    在java的com包中,新建包controller,在包中創建控制器類:==EmployeeController==

    @Controller
    public class EmployeeController{
    //測試使用
    @GetMapping("/test")
    //註解:返回JSON格式
    @ResponseBody
    public String test() {
    return "test";
    }
    }

    啟動主程式類,在瀏覽器中輸入:http://localhost:8080/test


四.開始編寫

  1. 編寫ORM實體類

    在java的com包中,新建包domain,在包中創建實體類:Employee

    public class Employee {
        private Integer id;   //主鍵
        private String name;  //員工姓名
        private String sex;   //員工性別
        private String phone; //電話號碼
    
        }

    ==不要忘記封裝==

  2. 完成mapper層==增刪改查==編寫

    在java的com包中,新建包mapper,在包中創建Mapper介面文件:EmployeeMapper

    //表示該類是一個MyBatis介面文件
    @Mapper
    //表示具有將資料庫操作拋出的原生異常翻譯轉化為spring的持久層異常的功能
    @Repository
    public interface EmployeeMapper {
        //根據id查詢出單個數據
        @Select("SELECT*FROM t_employee WHERE id=#{id}")
        Employee findById(Integer id);
    
        //查詢所有數據
        @Select("SELECT * FROM t_employee")
        public List<Employee> findAll();
    
        //根據id修改數據
        @UpdateProvider(type = EmployeeMapperSQL.class,method = "updateEmployee")
        int updateEmployee(Employee employee);
    
        //添加數據
        @Insert("INSERT INTO t_employee(name,sex,phone)  values(#{name},#{sex},#{name})")
        public int inserEm(Employee employee);
    
        //根據id刪除數據
        @Delete("DELETE FROM t_employee WHERE id=#{id}")
        public int deleteEm(Integer id);
    }
    
  3. 完成service層編寫,為controller層提供調用的方法

    1. 在java的com包中,新建包service,在包中創建service介面文件:EmployeeServic

         ```java
        public interface EmployeeService {
            //查詢所有員工對象
            List<Employee> findAll();
            //根據id查詢單個數據
            Employee findById(Integer id);
            //修改數據
            int updateEmployee(Employee employee);
            //添加數據
            int addEmployee(Employee employee);
            //刪除
            int deleteEmployee(Integer id);
        }
    2. 在service包中,新建包impl,在包中創建介面的實現類:EmployeeServiceImpl

      @Service
      //事物管理
      @Transactional
      public class EmployeeServiceImpl implements EmployeeService {
          //註入EmployeeMapper介面
          @Autowired
          private EmployeeMapper employeeMapper;
          //查詢所有數據
          public List<Employee> findAll() {
              return employeeMapper.findAll();
          }
      
          //根據id查詢單個數據
          public Employee findById(Integer id) {
              return employeeMapper.findById(id);
          }
      
          //修改數據
          public int updateEmployee(Employee employee) {
              return employeeMapper.updateEmployee(employee);
          }
      
          //添加
          public int addEmployee(Employee employee) {
              return employeeMapper.inserEm(employee);
          }
      
          //根據id刪除單個數據
          public int deleteEmployee(Integer id) {
              return employeeMapper.deleteEm(id);
          }
      }
  4. 完成Controller層編寫,調用serivce層功能,響應頁面請求

    在先前創建的controller.EmployeeController中編寫方法

    @Controller
    public class EmployeeController {
    
        @Autowired
        private EmployeeService employeeService;
    
    //主頁面  
        //響應查詢所有數據,然後顯示所有數據
        @GetMapping("/getall")
        public String getAll(Model model) {
            List<Employee> employeeList = employeeService.findAll();
            model.addAttribute("employeeList", employeeList);
            return "showAllEmployees";
        }
    
    //修改頁面
        //響應到達更新數據的頁面
        @GetMapping("/toUpdate/{id}")
        public String toUpdate(@PathVariable Integer id, Model model){
            //根據id查詢
            Employee employee=employeeService.findById(id);
            //修改的數據
            model.addAttribute("employee",employee);
            //跳轉修改
            return "update";
        }
    
        //更新數據請求並返回getall
        @PostMapping("/update")
        public String update(Employee employee){
            //報告修改
            employeeService.updateEmployee(employee);
            return "redirect:/getall";
        }
    
    //刪除功能
        //響應根據id刪除單個數據,然後顯示所有數據
        @GetMapping("/delete/{id}")
        public String delete(@PathVariable Integer id){
            employeeService.deleteEmployee(id);
            return "redirect:/getall";
        }
    
    //添加頁面
        //添加數據
        @PostMapping("/add")
        public String addEmployee(Employee employee){
            employeeService.addEmployee(employee);
            return "redirect:/getall";
        }
    }

五.編寫前端

  1. 主頁面

    在resouces的templates中,創建主頁面:addEmployee.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.prg">
    <head>
        <meta charset="UTF-8">
        <title>添加員工信息</title>
    </head>
    <body>
    <h2>添加員工信息</h2>
    <form action="/add" method="post">
        姓名:<input type="text" name="name"><br>
        性別:<input type="radio" value="男" name="sex" checked="checked">男
        <input type="radio" value="女" name="sex" >女<br>
        電話:<input type="text" name="phone"><br>
        <input type="submit" value="添加">
    </form>
    </body>
    </html>

    註意<html lang="en" ==xmlns:th="http://www.thymeleaf.prg"==>

  2. 修改頁面

    resouces的templates中,創建修改頁面:update.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>修改信息</title>
    </head>
    <body>
    <h2>修改信息</h2>
    <form th:action="@{/update}" th:object="${employee}" method="post">
        <input th:type="hidden" th:value="${employee.id}" th:field="*{id}">
        姓名:<input th:type="text" th:value="${employee.name}" th:field="*{name}"><br>
        性別:<input th:type="radio" th:value="男" th:checked="${employee.sex=='男'}" th:field="*{sex}">男
        <input th:type="radio" th:value="女" th:checked="${employee.sex=='女'}" th:field="*{sex}">女<br>
        電話:<input th:type="text" th:value="${employee.phone}" th:field="*{phone}"><br>
        <input th:type="submit" value="更新">
    </form>
    
    </body>
    </html>
  3. 添加頁面

    resouces的templates中,創建添加頁面:addEmployee.html

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.prg">
    <head>
        <meta charset="UTF-8">
        <title>添加員工信息</title>
    </head>
    <body>
    <h2>添加員工信息</h2>
    <form action="/add" method="post">
        姓名:<input type="text" name="name"><br>
        性別:<input type="radio" value="男" name="sex" checked="checked">男
        <input type="radio" value="女" name="sex" >女<br>
        電話:<input type="text" name="phone"><br>
        <input type="submit" value="添加">
    </form>
    </body>
    </html>

    啟動主程式類,在瀏覽器中輸入:http://localhost:8080/getall


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.PHP語法基礎是否都會,比如異常捕捉,面向對象,數組操作語法,字元串操作,cookie,session,全局變數,超全局數組,防止sql註入,mysql預處理 2.MYSQL基礎語法,欄位設計,原生sql語句,如何優化查詢效率,索引如何使用,分組聚合,表關聯(一對多,多對多),分庫分表, 3.服 ...
  • 如何使用python將大量數據導出到Excel中的小技巧 (1) 問題描述:為了更好地展示數據,Excel格式的數據文件往往比文本文件更具有優勢,但是具體到python中,該如何導出數據到Excel呢?如果碰到需要導出大量數據又該如何操作呢?本文主要解決以上兩個問題。 PS註意:很多人學Python ...
  • 視頻地址:https://www.bilibili.com/video/av59676843/?p=631 課件、源碼及習題:鏈接:https://pan.baidu.com/s/1Jt59yZfuK-4j7sYZgzmUqA 提取碼:yz8l 習題答案:https://www.cnblogs.co ...
  • 1、Mac下安裝requests庫: pip3 install requests 2、requests庫的使用 2.1 發送請求 使用Requests發送網路請求第一步,導入requests模塊: import requests 嘗試獲取某個網頁。如百度首頁: r = requests.get('h ...
  • 1. 起因 ​ 使用springboot也有些時間,一直很好奇它如何做到自動配置的,所以查閱了相關資料並且學習了相關內容,才寫了這篇文章。 2. 分析 ​ ①第一步我們從它的啟動配置類(XxxApplication)收起,我們進入到他的@SpringBootApplication註解。 ​ ②我們可 ...
  • 曾有邪教稱1999年12月31日是世界末日,當然該謠言已經不攻自破。 還有人稱今後的某個世紀末的12月31日,如果是星期一則會..…. 有趣的是,任何一個世紀末的年份的12月31日都不可能是星期一!!! 於是,“謠言製造商”又修改為星期日...... 1999年的12月31日是星期五,請問:未來哪一 ...
  • 前言 我們都知道redis是常駐在記憶體當中的,因此他的效率比MySQL要快很多很多。但又引發了另外一個問題,記憶體從本質上講,它是昂貴的,不能用於大量的長時間的存儲,他是“不安全不穩定的“,並且有可能存在記憶體泄露,不能與磁碟相比。 那麼如果解決這種問題呢?因此我們使用redis的時候,強制的應該給每個 ...
  • 一.前言 在講解 str / bytes /unicode區別之前首先要明白位元組和字元的區別,請參考:bytearray/bytes/string區別 中對位元組和字元有清晰的講解,最重要是明白: 字元str是給人看的,例如:文本保存的內容,用來操作的; 位元組bytes是給電腦看的,例如:二進位數據 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...